gpt4 book ai didi

c - fstat() st_nlink=1 即使在链接更多文件之后

转载 作者:行者123 更新时间:2023-12-02 22:22:26 24 4
gpt4 key购买 nike

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
struct stat buf;
int fd;

if (fd = open(argv[1], O_RDWR | O_CREAT)<0)
{
printf("file open error\n");
return 1;
}
if (link(argv[1], "link1") + link(argv[1], "link2")<0)
{
printf("error link\n");
return 1;
}
if (fstat(fd, &buf)<0)
{
printf("error fstat\n");
return 1;
}
printf("nlinks before = %d \n", buf.st_nlink);
if (unlink("link2") + unlink("link1") + unlink(argv[1])<0)
{
printf("unlink error\n");
return 1;
}
if (fstat(fd, &buf)<0)
{
printf("error fstat\n");
return 1;
}
printf("nlinks after = %d \n", buf.st_nlink);
return 0;
}

输出: 之前的 n 个链接 = 1 nlinks after = 1

为什么 st_nlink 总是 = 1,即使文件至少有 3 个链接?另外,如果我改用 lstat,我会得到 3 个 st_nlink。为什么?

最佳答案

if (fd = open(argv[1], O_RDWR | O_CREAT)<0)

应该是:

if ( (fd = open(argv[1], O_RDWR | O_CREAT))<0) 

作为<有更高的precedence= .

关于c - fstat() st_nlink=1 即使在链接更多文件之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487240/

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