【问题标题】:Confused with the st_ino?对 st_ino 感到困惑?
【发布时间】:2016-09-05 05:31:09
【问题描述】:
#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 得到一个 struct stat,st_ino 与 ls -i 的 i-node 编号相同。

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

如果我使用函数 fstat,则 st_ino 始终是 4195126。

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

【问题讨论】:

  • 你注释掉的open调用是错误的;第二个参数应该是合适的标志,而不是字符串。另外,请发布完整的代码,展示您如何使用fstat

标签: c stat fstat


【解决方案1】:

问题是您没有正确使用open,并且没有检查返回值是否有错误。所以你然后在open错误返回的无效文件描述符值-1上调用fstat,这也会失败并且根本不会触及buf,所以结构中未初始化的垃圾仍然存在(@ 987654327@, hex 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 2012-07-22
    • 2013-05-13
    • 2020-04-16
    • 2023-03-08
    • 2019-08-04
    • 2019-12-30
    • 2022-01-20
    相关资源
    最近更新 更多