0
#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?

inmove shawn
  • 189
  • 1
  • 2
  • 9
  • The `open` call that you have commented out is wrong; the second parameter should be suitable flags, not a string. Also, please post complete code showing how you use `fstat`. – davmac May 10 '16 at 10:03

1 Answers1

2

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;
}
CherryDT
  • 25,571
  • 5
  • 49
  • 74