Get the real path of a symbolic link

Suppose I want to get the real path of a symbolic link. I know that the readlink and stat system calls can dereference the link and give me a real way. Do they work the same way (only regarding dereferencing, I know stat does a lot more)? Should I give preference to another?

+4
source share
2 answers

Use stat() to tell you about the file at the end of any chain of symbolic links; it will not lead you to the path in any way. Use lstat() to get information about a symbolic link, if any, called; it acts like stat() when the specified name is not a symbolic link. Use readlink() to get the path name stored in the symbolic link named as its argument (beware - this does not mean that null terminates the line).

If you need the full path to the file at the end of the symlink, you can use realpath() . This gives you an absolute path name that does not cross any symbolic links to access the file.

+8
source

Yes, you should use readlink() for this. However, note that this requires that you allocate a buffer to hold the dereferenced path. lstat() can help if you want to allocate the exact size buffer that is required, as shown in the example below readlink() man page .

+1
source

Source: https://habr.com/ru/post/1496289/


All Articles