如何确定文件是否为链接?

18

我有以下代码这里只显示了其中一部分,我正在检查文件的类型。

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);时,获取st_mode值为33188。

我用一个普通文件类型和一个符号链接测试了我的程序。在两种情况下输出结果都是"regular file",即符号链接的情况失败了,我不明白为什么?


问题有点不清楚。您是在测试符号链接,而程序说它是一个常规文件吗?buf.st_mode的值是多少? - Gintautas Miliauskas
6
你需要使用lstat()stat()会跟随符号链接并检查它们所指向的文件。 - Michael Foukarakis
1个回答

39

stat (2)手册中可得知:

stat()函数返回由路径path指定的文件统计信息,并将结果保存在buf所指的结构体中。

lstat()函数与stat()函数基本相同,区别在于如果路径path是一个符号链接,则返回的是符号链接本身的stat信息,而不是它所指向的文件的信息。

换句话说,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

像预期的那样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接