Linux 如何判断一个文件是否是一个链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3984948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:44:48  来源:igfitidea点击:

How to figure out if a file is a link?

clinuxsymlinksystem-callsstat

提问by Eternal Learner

I have the below code only a part of it is shown hereand I am checking if a the type of file.

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

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

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

问题:st_mode当我做printf("\nMode: %d\n",buf.st_mode);结果时获得的值为33188。

I tested my program with a regular file type and a symbolic link. In both cases the output was "regular file" i.e the symbolic link case is failing and I fail to understand why?

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

采纳答案by paxdiablo

From the stat (2)man page:

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()统计 path 指向的文件并填写buf.

lstat()与 相同stat(),除了如果 path 是符号链接,则链接本身是 stat-ed,而不是它引用的文件。

In other words, the statcall will follow the symbolic link to the target file and retrieve the information for that.Try using lstatinstead, it will give you the information for the link.

换句话说,stat调用将遵循指向目标文件的符号链接并检索该文件的信息尝试使用lstat,它会给你链接的信息



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 will get:

你会得到:

 stat says file
lstat says link

as expected.

正如预期的那样。