Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

symlink

inode

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!

like image 783
hora Avatar asked Apr 14 '10 08:04

hora


People also ask

How do you know if a link is symbolic or hard?

A symbolic link is a link to another name in the file system. Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode.

Does stat follow symlinks?

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). You use stat() when you want links to behave in the "normal way", i.e. as the file they point at.

What is stat () in C?

The stat() function gets status information about a specified file and places it in the area of memory pointed to by the buf argument. If the named file is a symbolic link, stat() resolves the symbolic link. It also returns information about the resulting file.


1 Answers

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.

like image 56
unwind Avatar answered Sep 28 '22 01:09

unwind