How do you determine using stat() whether a file is a symbolic link?
Asked Answered
D

1

18

I basically have to write a clone of the UNIX ls command for a class, and I've got almost everything working. One thing I can't seem to figure out how to do is check whether a file is a symbolic link or not. From the man page for stat(), I see that there is a mode_t value defined, S_IFLNK.

This is how I'm trying to check whether a file is a sym-link, with no luck (note, stbuf is the buffer that stat() returned the inode data into):

switch(stbuf.st_mode & S_IFMT){
    case S_IFLNK:
        printf("this is a link\n");
        break;
    case S_IFREG:
        printf("this is not a link\n");
        break;
}

My code ALWAYS prints this is not a link even if it is, and I know for a fact that the said file is a symbolic link since the actual ls command says so, plus I created the sym-link...

Can anyone spot what I may be doing wrong? Thanks for the help!

Diplopia answered 14/4, 2010 at 8:34 Comment(1)
Citing from my stat(2) manpage: lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.Dara
C
30

You can't.

You need to use lstat() to stat the link itself, plain stat() will follow the link, and thus never "see" the link itself.

Contrail answered 14/4, 2010 at 8:39 Comment(4)
So why would you use the stat() command then? I just tried using lstat() and it seems like it provides the same information, except it handles links. Would you use stat() only when you know you're not dealing with any sym-links?Diplopia
You also use it when dealing with symlinks, often times you don't care whether the path is a regular file or a link, you care about the file that is used. For instance mtime for the link is completely uninteresting, mtime for the file the link is pointing to is.Fructidor
stat() does handle links, it just handles them differently - it follows the link and tells you about the file that it points to (which, as wich points out, is oftentimes what you want).Gambado
You use stat() when you want links to behave in the "normal way", i.e. as the file they point at. Only applications that need to differentiate between links and non-links need to use lstat().Contrail

© 2022 - 2024 — McMap. All rights reserved.