How to determine if a file is a link?

I have the code below, only part of it is shown here, and I check if there is a file type.

struct stat *buf /* just to show the type buf is*/ switch (buf.st_mode & S_IFMT) { case S_IFBLK: printf(" block device\n"); break; case S_IFCHR: printf(" character device\n"); break; case S_IFDIR: printf(" directory\n"); break; case S_IFIFO: printf(" FIFO/pipe\n"); break; case S_IFLNK: printf(" symlink\n"); break; case S_IFREG: printf(" regular file\n"); break; case S_IFSOCK: printf(" socket\n"); break; default: printf(" unknown?\n"); break; } 

Problem: st_mode value obtained when I do a printf("\nMode: %d\n",buf.st_mode); , the result is 33188.

I tested my program with the usual file type and symlink. In both cases, the output was a "regular file", i.e. The symlink case fails, and I don't understand why?

+7
c linux system-calls symlink stat
source share
1 answer

On the stat (2) page:

stat() sets the file pointed to by the path and buf populated.

lstat() is identical to stat() , except that if the path is a symbolic link, then the link itself is set, and not the file to which it refers.

In other words, the stat call will follow a symbolic link to the target file and receive information for this. Try using lstat instead, it will provide you with information for reference.


If you do the following:

 touch junkfile ln -s junkfile junklink 

then compile and run the following program:

 #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main (void) { struct stat buf; int x; x = stat ("junklink", &buf); if (S_ISLNK(buf.st_mode)) printf (" stat says link\n"); if (S_ISREG(buf.st_mode)) printf (" stat says file\n"); x = lstat ("junklink", &buf); if (S_ISLNK(buf.st_mode)) printf ("lstat says link\n"); if (S_ISREG(buf.st_mode)) printf ("lstat says file\n"); return 0; } 

You'll get:

  stat says file lstat says link 

as was expected.

+14
source share

All Articles