如何确定符号链接指向的文件的路径? [英] How do you determine the path of the file that a symlink points to?

查看:147
本文介绍了如何确定符号链接指向的文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中,如果您知道一个文件的路径是一个符号链接,那么如何以编程方式(使用C或C ++)确定它指向的文件的路径?

In Linux, if you have a path to a file which you know is a symlink, how do you programmatically determine (in C or C++) the path to the file that it points to?

推荐答案

readlink 函数。做一个 man 2 readlink 。这个函数是Posix API的一部分,所以它几乎可以在任何Unix上工作。

The readlink function. Do a man 2 readlink. This function is part of the Posix API, so it should work on almost any Unix.

如果路径以'/ code>,那么它是一个绝对符号链接,你有它所引用的文件的完整的绝对路径(这可能是另一个符号链接,你必须重复该过程)。

If the path starts with a '/', then its an absolute symlink and you have the full absolute path of the file to which it refers (which may be another symbolic link, and you'll have to repeat the process again).

如果路径不以' / '开头,那么它是一个相对链接,并相对于符号链接所在的目录

If the path does not start with '/', then it's a relative link and is interpreted relative to the directory the symlink is in. It's up to you to combine the path appropriately to figure out the real filename.

当然,有些符号链接用于存储实际上不是路径的信息。有时程序在其中存储PID或其他这样的信息用于锁定目的。

Of course, sometimes symlinks are used to store information that's not actually a path. Sometimes programs store a PID or other such information in them for locking purposes. The calls to create a symlink are one of the more reliably atomic operations that can be performed on an NFS mounted filesystem.

此外,在我的Fedora系统上,如果你执行 man 7 symlink 你会对符号链接,它们在各种情况下的行为以及操作它们或受它们影响的函数的详细讨论。

Also, on my Fedora system, if you do man 7 symlink you get a long discussion of symlinks, their behavior in various circumstances and a rundown of the functions that manipulate them or are affected by them.

这篇关于如何确定符号链接指向的文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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