2017-09-25 177 views
-2

我正在使用下面的代碼將文件名保存到數組中。我從這裏得到了代碼save file names to an array。當我運行這段代碼時,它說目錄中有5個文件(即count是5),但是,只有3個。有人可以驗證這是否正確或我犯了一個錯誤?在c目錄中列出文件

#include <string.h> 
#include <stdio.h> 
#include <dirent.h> 
#include <malloc.h> 

size_t file_list(const char *path, char ***ls) { 
    size_t count = 0; 
    size_t length = 0; 
    DIR *dp = NULL; 
    struct dirent *ep = NULL; 

    dp = opendir(path); 
    if(NULL == dp) { 
     fprintf(stderr, "no such directory: '%s'", path); 
     return 0; 
    } 

    *ls = NULL; 
    ep = readdir(dp); 
    while(NULL != ep){ 
     count++; 
     ep = readdir(dp); 
    } 

    rewinddir(dp); 
    *ls = calloc(count, sizeof(char *)); 

    count = 0; 
    ep = readdir(dp); 
    while(NULL != ep){ 
     (*ls)[count++] = strdup(ep->d_name); 
     ep = readdir(dp); 
    } 

    closedir(dp); 
    return count; 
} 

int main(int argc, char **argv) { 

    char **files; 
    size_t count; 
    int i; 

    count = file_list("/home/rgerganov", &files); 
    for (i = 0; i < count; i++) { 
     printf("%s\n", files[i]); 
    } 
} 
+9

它可能正在計算'.'和'..'。 –

+2

你有沒有試過打印你得到的文件的名字?或者更好,但嘗試在調試器中逐步執行程序? –

+0

@EugeneSh。是的,這正是它正在做的!什麼是'.'和'..'?謝謝 –

回答

1

幾個月前我問自己同一個學校項目的問題。當你使用dirent結構並且列出訪問元素d_name時,它實際上會計算目錄加上「。」。和「..」,所以這是正常的。如果您不想將它們作爲目錄,只需爲循環創建一個迭代器變量並添加如下條件:

int i = 0; 
while (condition) 
{ 
    if (ep->d_name[i] == '.') 
    { 
     ++i; 
    } 
    //do stuff here 
} 
+0

AND-ed條件不是必需的。對於以'.'開始的所有名稱以及以兩個'..'開頭的所有名稱,您都希望條件等同於true。後一種情況下的每個名字都將以*。開頭。因此你的條件可以簡化爲'if(ep-> d_name [i] =='。'){}'。 – Toby

+1

是的,這是真的,不知道爲什麼我把第二個。感謝我編輯! – joemartin94

+0

謝謝你們非常有幫助的建議! –