How do you determine the path of the file that a symlink points to?
In Linux, if you have a path to a file which you know is a symlink, how do you 开发者_JAVA技巧programmatically determine (in C or C++) the path to the file that it points to?
The readlink
function. Do a man 2 readlink
. This function is part of the Posix API, so it should work on almost any Unix.
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.
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.
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.
On POSIX or BSD system use readlink()
精彩评论