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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
readlinkfunction. Do aman 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 symlinkyou 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.