int main(int argc, char *argv[]) { struct stat buf; //int fd = open("./fstatat.c", "r"); //int fd2 = fstatat(" /> int main(int argc, char *argv[]) { struct stat buf; //int fd = open("./fstatat.c", "r"); //int fd2 = fstatat(" /> int main(int argc, char *argv[]) { struct stat buf; //int fd = open("./fstatat.c", "r"); //int fd2 = fstatat("/>

Confused with the st_ino?

1.3k Views Asked by At
#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;
}

if i use the function stat to get a struct stat, the st_ino is the same as the i-node number with the ls -i.

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

buf if i use the function fstat, the st_ino is always the 4195126.

anyone can tell me why this happen?

1

There are 1 best solutions below

0
CherryDT On

The problem is that you are not using open correctly and don't check the return values for errors. So you are then calling fstat on the invalid file descriptor value -1 returned by open on error, which will also fail and not touch buf at all, so the uninitialized garbage in the struct is still there (4195126, hex 0x400336 smells a lot like a return address of a previous function call still being on the stack or something like this.)

As davmac already pointed out, the second parameter to open must be a list of flags, which are numeric. Check the docs.

So, the correct code would be:

#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;
}