#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?
The problem is that you are not using
opencorrectly and don't check the return values for errors. So you are then callingfstaton the invalid file descriptor value-1returned byopenon error, which will also fail and not touchbufat all, so the uninitialized garbage in the struct is still there (4195126, hex0x400336smells 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
openmust be a list of flags, which are numeric. Check the docs.So, the correct code would be: