简体   繁体   English

获取符号链接的真实路径

[英]Get real path of a symlink

Suppose that I want to get the real path of a symlink. 假设我想获得符号链接的真实路径。 I know that both readlink and stat system calls can dereference the link and give me its real path. 我知道readlinkstat系统调用都可以取消引用链接并给我真正的路径。 Do they operate in the same way (only regarding the dereferencing, I know that stat does lots more)? 它们是否以相同的方式运行(仅关于解除引用,我知道stat做更多的事情)? Should I prefer one over the other? 我应该更喜欢一个吗?

Use stat() to tell you about the file at the end of any chain of symlinks; 使用stat()告诉你任何符号链的末尾的文件; it does not get you the path in any way. 它不会以任何方式让你走上正轨。 Use lstat() to get information about the symlink, if any, that is referred to; 使用lstat()获取有关所引用的符号链接的信息(如果有); it acts like stat() when the name given is not a symlink. 当给定的名称不是符号链接时,它就像stat() Use readlink() to obtain the path name stored in the symlink named as its argument (beware — it does not null terminate the string). 使用readlink()获取存储在符号链接中的路径名,该路径名称作为其参数(注意 - 它不会终止字符串)。

If you want the full pathname of the file at the end of the symlink, you can use realpath() . 如果要在符号链接末尾使用文件的完整路径名,可以使用realpath() This gives you an absolute pathname which does not cross any symlinks to reach the file. 这将为您提供绝对路径名,该路径名不会跨越任何符号链接以到达文件。

Yeah, you should use readlink() for that. 是的,你应该使用readlink() However, notice that it requires that you allocate a buffer to store the dereferenced path in. lstat() can help if you want to allocate a buffer of the exact size that is required, as is shown in the example at the bottom of the readlink() man page . 但是,请注意,它需要您分配一个缓冲区来存储取消引用的路径。如果您想要分配所需大小的缓冲区, lstat()可以提供帮助,如readlink()底部的示例所示readlink() 手册页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM