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

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

问题描述

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

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

解决方案

使用 realpath().

<块引用>

realpath() 函数应派生,从指向的路径名file_name,一个绝对路径名命名相同的文件,其分辨率不涉及 '.', '..', 或符号链接.生成的路径名应存储为空终止字符串,最多为 {PATH_MAX}字节,在指向的缓冲区中resolved_name.

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

<小时><块引用>

以下示例生成一个文件的绝对路径名由符号链接路径标识争论.生成的路径名是存储在实际路径数组中.

#include ...char *symlinkpath = "/tmp/symlink/file";char 实际路径 [PATH_MAX+1];字符 *ptr;ptr = realpath(符号链接路径,实际路径);

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天全站免登陆