获取文件的绝对路径 [英] Getting absolute path of a file

查看:186
本文介绍了获取文件的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能转换成一个相对路径在C在Unix上的绝对路径?
是否有一个方便的系统功能为这个?

在Windows中有一个 GetFullPathName 功能,没有工作,但我没有找到在Unix类似的东西...


解决方案

使用真实路径()


  

的真实路径()功能应派生,
  从路径指向
   FILE_NAME ,一个绝对路径名
  名相同的文件,其分辨率
  不涉及 .. ,或
  符号链接。生成的路径
  应存储为空值终止
  字符串,最多的 {PATH_MAX}
  字节,在缓冲区指向
   resolved_name


  
  

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




  

下面的例子生成
  绝对路径的文件
  经鉴定symlinkpath
  论据。生成的路径名
  存储在actualpath阵列中的


 的#include<&stdlib.h中GT;
...
字符* symlinkpath =/ tmp目录/符号链接/文件;
焦炭actualpath [PATH_MAX + 1];
字符* PTR;
PTR =真实路径(symlinkpath,actualpath);

How can I convert a relative path to an absolute path in C on Unix? Is there a convenient system function for this?

On Windows there is a GetFullPathName function that does the job, but I didn't find something similar on Unix...

解决方案

Use realpath().

The realpath() function shall derive, from the pathname pointed to by file_name, an absolute pathname that names the same file, whose resolution does not involve '.', '..', or symbolic links. The generated pathname shall be stored as a null-terminated string, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolved_name.

If resolved_name is a null pointer, the behavior of realpath() is implementation-defined.


The following example generates an absolute pathname for the file identified by the symlinkpath argument. The generated pathname is stored in the actualpath array.

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


ptr = realpath(symlinkpath, actualpath);

这篇关于获取文件的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆