如何在Unix上将相对路径转换为C中的绝对路径? 有没有方便的系统功能呢?

在Windows上有一个 GetFullPathName 函数来完成这项工作,但我在Unix上找不到类似的东西......

有帮助吗?

解决方案

使用 realpath()

  

realpath()函数应该派生,   从指向的路径名    file_name ,一个绝对路径名   命名相同的文件,其分辨率   不涉及'',' .. ',或   象征性的联系。生成的路径名   应存储为以空值终止的   字符串,最多为 {PATH_MAX}   字节,在指向的缓冲区中   <代码> resolved_name

     

如果 resolved_name 是空指针,    realpath()的行为是   实现定义的。


  

以下示例生成一个   文件的绝对路径名   由symlinkpath标识   论点。生成的路径名是   存储在actualpath数组中。

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


ptr = realpath(symlinkpath, actualpath);

其他提示

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);
}

也可以尝试“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.

还有一个小型路径库 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top