2017-09-25 173 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

谢谢你们非常有帮助的建议! –