stat not working

stat not working

本文关键字:working not stat      更新时间:2023-10-16

我正在编写一个文件观察程序,由于某些原因,stat无法获取文件信息,为什么?


struct stat info;
int fd = open(path, O_EVTONLY);
if (fd <= 0){
    exit(-1);
}
int result = fstat(fd, &info);
if (!result){
    exit(-1); //This happens! Errno says "No such file or directory" but that cant be because open would've failed
}
int result = fstat(fd, &info);
if (!result){
    exit(-1);
}

检查fstat手册页,成功时返回0。

stat在成功时返回零,大多数标准libc函数也是如此。

这是这样设计的,所以你可以很容易地检查库调用链中的错误:

if (stat(fd, &info)) {
    perror("stat");
    exit(1);
}
//stat succeeded.
if (...) {
}

根据您的用法,我认为您想要fstat()。fstat()使用fd作为参数,stat()使用字符串。