C语言 如何使用 stat() 确定文件是否为符号链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2635923/
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-09-02 05:10:05  来源:igfitidea点击:

How do you determine using stat() whether a file is a symbolic link?

csymlinkinode

提问by hora

I basically have to write a clone of the UNIX ls command for a class, and I've got almost everything working. One thing I can't seem to figure out how to do is check whether a file is a symbolic link or not. From the manpage for stat(), I see that there is a mode_tvalue defined, S_IFLNK.

我基本上必须为一个类编写一个 UNIX ls 命令的克隆,并且我几乎所有的东西都在工作。我似乎无法弄清楚如何做的一件事是检查文件是否是符号链接。从 的手册页中stat(),我看到mode_t定义了一个值,S_IFLNK

This is how I'm trying to check whether a file is a sym-link, with no luck (note, stbuf is the buffer that stat()returned the inode data into):

这就是我试图检查文件是否是符号链接的方式,但没有运气(注意,stbuf 是stat()将 inode 数据返回到的缓冲区):

switch(stbuf.st_mode & S_IFMT){
    case S_IFLNK:
        printf("this is a link\n");
        break;
    case S_IFREG:
        printf("this is not a link\n");
        break;
}

My code ALWAYS prints this is not a linkeven if it is, and I know for a fact that the said file is a symbolic link since the actual ls command says so, plus I created the sym-link...

我的代码总是打印,this is not a link即使它是,而且我知道一个事实,即所述文件是一个符号链接,因为实际的 ls 命令是这样说的,而且我创建了符号链接...

Can anyone spot what I may be doing wrong? Thanks for the help!

谁能发现我可能做错了什么?谢谢您的帮助!

回答by unwind

You can't.

你不能。

You need to use lstat()to stat the link itself, plain stat()will follow the link, and thus never "see" the link itself.

您需要使用lstat()stat 链接本身,plainstat()将跟随链接,因此永远不会“看到”链接本身。