Get real path of a symlink

c, linux

Solution

Use `stat()` to tell you about the file at the end of any chain of symlinks; it does not get you the path in any way. Use `lstat()` to get information about the symlink, if any, that is referred to; it acts like `stat()` when the name given is not a symlink. Use `readlink()` to obtain the path name stored in the symlink named as its argument (beware — it does not null terminate the string).

If you want the full pathname of the file at the end of the symlink, you can use `realpath()`. This gives you an absolute pathname which does not cross any symlinks to reach the file.

Problem

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. Do they operate in the same way (only regarding the dereferencing, I know that `stat` does lots more)? Should I prefer one over the other?

Original source