Paco Muñoz Martinez Paco Muñoz Martinez - 26 days ago 9
Linux Question

How to differentiate between a regular file and a symbolic link?

I am dealing with symbolic links using C posix in linux.

I detect a file and I have to differentiate between a regular file and a symbolic link.

Now I do the next:

if(S_ISREG(direct_info.st_mode)) {
// deal with regular file
}
else if(S_ISLNK(direct_info.st_mode)) {
// deal with symbolic link
}


the problem is that when the file is a symbolic link the flow of the execution enter at the first if. That is, when is a symbolic link also enter in the
S_ISREG
condition. So, what can i do to distinguish between both?

Answer

You are probably using stat() to get the file modes. stat() actually returns the info about the target, not the link itself. So, in order to get the information about the link itself you need to use lstat().