2016-05-10 3 views
-1
#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; 
} 

stを使用してstruct statを取得する場合、st_inoはls -iのiノード番号と同じです。st_inoと混同されていますか?

1305609 
[[email protected] chapter-four]$ ls -i 
1305607 a.txt 1305606 fstatat.bin 1305609 fstatat.c 1305605 tmp.txt 

BUF iの関数FSTATを使用している場合、st_inoのは常にこれが起こる理由4195126.

誰も教えてもらえますか?

+0

あなたがコメントアウトされている 'open'呼び出しが間違っています。 2番目のパラメータは文字列ではなく適切なフラグでなければなりません。また、 'fstat'の使い方を示す完全なコードを投稿してください。 – davmac

答えて

2

openを正しく使用していないため、エラーの戻り値をチェックしないという問題があります。以下のようにたくさんのにおい0x400336進、4195126(だから、その後も全くbufを触れ失敗しませんエラーにopenによって返された無効なファイルディスクリプタ値-1、上fstatを呼び出しているので、構造体の初期化されていないごみはまだそこにありますスタック上にある前の関数呼び出しの戻りアドレスまたはこのようなもの)

davmacはすでに指摘したように、openの2番目のパラメータはフラグのリストでなければなりません。数値です。 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; 
} 
+0

ああ、thx、私はとても不注意だった。 –

関連する問題