2016-11-30 25 views
0

我想列出文件的相關信息(包括目錄等)使用的stat()什麼是錯的,在linux下用C我的stat()函數

當我給它工作正常「」(當前目錄)的argv [1](實施例$。/ a.out的。)

但是有一個錯誤,當我給其他目錄,如 「..」, 「/」 等

統計函數返回-1(失敗)在direntp指向「..」(父目錄)後。

這裏有一個例子。

$ ls -a .. 
. .. sample temple 

$ ./a.out .. 
Success: . 
Success: .. 
Fail: sample 
Stat Call Error. 
Terminate. 

$ 

那麼,爲什麼它失敗時,我給其他路徑stat()的參數?

這裏是我的代碼如下

 

    #include "stdio.h" 
    #include "dirent.h" 
    #include "sys/stat.h" 
    #include "unistd.h" 
    #include "stdlib.h" 

    int main(int argc, char const *argv[]) 
    { 
     DIR *dirp; 
     struct dirent *direntp; 
     struct stat statbuf; 

     dirp = opendir(argv[1]); 
     while((direntp = readdir(dirp)) != NULL) 
     { 
      if(direntp->d_ino == 0) 
       continue; 
      if(direntp->d_name[0] != '.'); /* doesn't matter, This isn't a mistake */ 
      { 
       if(stat(direntp->d_name, &statbuf) == -1) 
       { 
        printf("Fail: %s\n", direntp->d_name); 
        printf("Stat Call Error\n"); 
        exit(-1); 
       } 
       printf("Success: %s\n", direntp->d_name); 
      } 
     } 
     closedir(dirp); 
     return 0; 
    } 

+2

'如果(STAT(direntp-> d_name,&statbuf)d_name);':這是否編譯? –

+0

我修正了代碼。左括號被忽略因爲它被認爲是在html中的標籤,所以我改爲== -1 –

+2

'if(direntp-> d_name [0]!='。');'表示該行之後的所有內容都不考慮到'direntp-> d_name [0]' – KevinDTimm

回答

3

opendir函數返回使用相對路徑,而不是絕對的目錄內容。

當你不掃描當前目錄下,你只有條目的名稱,而不是它的完整路徑,所以stat上的所有條目失敗,因爲它看起來他們,在當前目錄(但...這也存在於當前目錄中)。

當然,它工作在當前目錄,你沒有這個問題。

修正:構成的完整路徑名,購自這樣的:

char fp[PATH_MAX]; 
sprintf(fp,"%s/%s",argv[1],direntp->d_name); 
if(stat(fp, &statbuf)) { 
... 
+0

謝謝,但我沒有完全理解。 如果我想在其他目錄上做同樣的事情,該怎麼辦? –

+1

創建完整路徑,請檢查我上面提出的代碼片段。 –

相關問題