gpt4 book ai didi

c - 如何判断文件是否为链接?

转载 作者:IT王子 更新时间:2023-10-29 00:04:30 24 4
gpt4 key购买 nike

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

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。

我用常规文件类型和符号链接(symbolic link)测试了我的程序。在这两种情况下,输出都是“常规文件”,即符号链接(symbolic link)案例失败,我不明白为什么?

最佳答案

来自stat (2)手册页:

stat() stats the file pointed to by path and fills in buf.

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.

换句话说,stat 调用将跟随目标文件的符号链接(symbolic link)并检索那个文件的信息。尝试使用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

正如预期的那样。

关于c - 如何判断文件是否为链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com