unix 获取文件的绝对路径

pcrecxhr  于 4个月前  发布在  Unix
关注(0)|答案(5)|浏览(52)

如何在Unix上的C中将相对路径转换为绝对路径?有没有方便的系统函数可以实现这一点?
在Windows上有一个GetFullPathName函数可以完成这项工作,但我在Unix上没有找到类似的东西。

xfb7svmp

xfb7svmp1#

请使用realpath()
realpath()函数应该从file_name指向的路径名派生一个命名同一文件的绝对路径名,其解析不涉及' . '、' .. '或符号链接。生成的路径名应该以null结尾的字符串形式存储在resolved_name指向的缓冲区中,最多可达{PATH_MAX}个字节。
如果resolved_name是空指针,则realpath()的行为由实现定义。
以下示例为symlinkpath参数标识的文件生成绝对路径名。生成的路径名存储在actualpath数组中。

#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;

ptr = realpath(symlinkpath, actualpath);

字符串

waxmsbnn

waxmsbnn2#

stdlib.h中尝试realpath()

char filename[] = "../../../../data/000000.jpg";
char* path = realpath(filename, NULL);
if(path == NULL){
    printf("cannot find file with name[%s]\n", filename);
} else{
    printf("path[%s]\n", path);
    free(path);
}

字符串

acruukt9

acruukt93#

还有一个小的路径库cwalk,它可以跨平台工作。它有cwk_path_get_absolute来做到这一点:

#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char buffer[FILENAME_MAX];

  cwk_path_get_absolute("/hello/there", "./world", buffer, sizeof(buffer));
  printf("The absolute path is: %s", buffer);

  return EXIT_SUCCESS;
}

字符串
产出:

The absolute path is: /hello/there/world

c6ubokkw

c6ubokkw4#

也可以试试“getcwd”

#include <unistd.h>

char cwd[100000];
getcwd(cwd, sizeof(cwd));
std::cout << "Absolute path: "<< cwd << "/" << __FILE__ << std::endl;

字符串
测试结果:

Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp


测试环境:

setivolkylany@localhost$/ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.6 (jessie)
Release:    8.6
Codename:   jessie
setivolkylany@localhost$/ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
setivolkylany@localhost$/ g++ --version
g++ (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

mklgxw1f

mklgxw1f5#

如果realpath()不存在(这是在windows的情况下),则使用_fullpath()

相关问题