2013-11-01 38 views
1

我有以下函數,抽象的統計結構的處理用C壞的結果而獲得文件的詳細信息Ç

int isdir(const char *filename) { 
    struct stat st_buf; 
    stat(filename, &st_buf); 
    if(S_ISDIR(st_buf.st_mode)) 
     return 0; 
    return 1; 
} 

和主函數調用isdir

int main(...) { 
    struct dirent *file; 
    DIR *dir = opendir(argv[1]); 

    while(file = readdir(dir)) { 
     printf("%d\n", isdir(file->d_name)); 
    } 
    closedir(dir); 
    /* other code */ 
} 

我有一個名爲Test文件夾作爲程序的參數,在兩個文件中,一個是名爲「archivo」的常規文件和一個名爲「carpeta」的文件夾。我的程序從文件和文件夾中打印1和1,當它應該是0和1時,我看不到錯誤在哪裏。

終端中運行的stat函數爲文件和文件夾提供輸出。

Fichero: «archivo» 
Tamaño: 0   Bloques: 0   Bloque E/S: 4096 fichero regular 
Dispositivo: 805h/2053d Nodo-i: 3159580  Enlaces: 1 
Acceso: (0664/-rw-rw-r--) Uid: (1000/alejandro) Gid: (1000/alejandro) 
Acceso: 2013-10-31 21:08:57.556446728 -0300 
Modificación: 2013-10-31 21:08:57.556446728 -0300 
    Cambio: 2013-10-31 21:08:57.556446728 -0300 
Creación: - 

Fichero: «carpeta/» 
Tamaño: 4096  Bloques: 8   Bloque E/S: 4096 directorio 
Dispositivo: 805h/2053d Nodo-i: 3147783  Enlaces: 2 
Acceso: (0775/drwxrwxr-x) Uid: (1000/alejandro) Gid: (1000/alejandro) 
Acceso: 2013-10-31 21:19:11.728526599 -0300 
Modificación: 2013-10-31 21:19:20.867833586 -0300 
Cambio: 2013-10-31 21:19:20.867833586 -0300 
Creación: - 
+1

你檢查stat的返回值嗎? –

回答

3

的問題是,file->d_name只是一個文件名,不包括目錄路徑。因此isdir()正在當前目錄中查找文件,而不是在argv[1]中指定的目錄。您需要將目錄傳遞到isdir(),然後在呼叫stat()之前將目錄和文件名與它們之間的/分隔符連接起來。

int isdir(const char *dirname, const char *filename) { 
    struct stat st_buf; 
    char *fullname = malloc(strlen(dirname)+strlen(filename)+2); // +2 for the slash and trailing null 
    strcpy(fullname, dirname); 
    strcat(fullname, "/"); 
    strcat(fullname, filename); 
    if (stat(fullname, &st_buf) == -1) { 
     perror(fullname); 
     free(fullname); 
     return 0; 
    } 
    free(fullname); 
    return !S_ISDIR(st_buf.st_mode); 
} 

那麼你應該把它叫做:

isdir(argv[1], file->d_name)); 
+0

優秀的答案,我用一個文件夾編寫我的想法,但代碼沒有在那裏工作哈哈。當你編輯答案時,我用你的strcpy和strcat重新編寫函數。 –

1

最有可能的stat失敗。請檢查:

if(-1 == stat(filename, &st_buf)) { 
    perror(filename); 
    return 0; 
} 
0

的另一個問題是,你在你的一邊打電話READDIR兩次,一次是()構建,一旦事後。它正在報告隱藏目錄的數據。和...

+0

上帝,翻譯問題,我試圖翻譯代碼,沒有工作,我會解決這個問題,但謝謝,在這種情況下,你也是對的。 –