gpt4 book ai didi

对 st_ino 感到困惑?

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:51 25 4
gpt4 key购买 nike

#include "stdio.h"
#include <sys/stat.h>

int
main(int argc, char *argv[]) {
struct stat buf;
//int fd = open("./fstatat.c", "r");
//int fd2 = fstatat(fd, "a.txt", &buf, 0);
//printf("%d\n", buf.st_ino);
stat("./fstatat.c", &buf);
printf("%d\n", buf.st_ino);
return 0;
}

如果我使用函数 stat 获取结构 stat,则 st_ino 与带 ls -i 的 i 节点编号相同。

1305609
[inmove@localhost chapter-four]$ ls -i
1305607 a.txt 1305606 fstatat.bin 1305609 fstatat.c 1305605 tmp.txt

buf 如果我使用函数 fstat,st_ino 总是 4195126。

谁能告诉我为什么会这样?

最佳答案

问题是您没有正确使用 open 并且没有检查返回值是否有错误。因此,您随后在 open 错误返回的无效文件描述符值 -1 上调用 fstat,这也会失败并且不会触及 buf,所以结构中未初始化的垃圾仍然存在(4195126,十六进制 0x400336 闻起来很像先前函数调用的返回地址仍在堆栈中或类似的东西。)

正如 davmac 已经指出的,open 的第二个参数必须是标志列表,它们是数字。检查docs .

所以,正确的代码应该是:

#include "stdio.h"
#include <sys/stat.h>
#include <sys/fcntl.h> // for the O_RDONLY constant
#include <errno.h> // for error output


int main(int argc, char *argv[]) {
struct stat buf;
int fd = open("./fstatat.c", O_RDONLY);
if(fd == -1) {
printf("Error calling open: %s\n", strerror(errno));
} else {
if(fstat(fd, &buf) == -1) {
printf("Error calling fstat: %s\n", strerror(errno));
} else {
printf("%d\n", buf.st_ino);
if(close(fd) == -1) {
printf("Error calling close: %s\n", strerror(errno));
}
}
}
return 0;
}

关于对 st_ino 感到困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37135110/

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