如何确定一个文件是否是一个链接?

我有下面的代码只有它的一部分显示在这里 ,我正在检查如果文件的types。

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; } 

问题:当我做一个printf("\nMode: %d\n",buf.st_mode); 结果是33188。

我用普通的文件types和符号链接testing了我的程序。 在这两种情况下,输出都是“常规文件”,即符号链接案例失败,我不明白为什么?

stat (2)手册页:

stat()统计path指向的文件并填充buf

lstat()stat() lstat()是相同的,只是如果path是一个符号链接,那么链接本身是stat- ed的,而不是它引用的文件。

换句话说, stat调用将跟随目标文件的符号链接并检索相关信息 尝试使用lstat代替,它会给你链接的信息


如果您执行以下操作:

 touch junkfile ln -s junkfile junklink 

然后编译并运行以下程序:

 #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; } 

你会得到:

  stat says file lstat says link 

如预期。