c - 列出c目录中的文件

标签 c arrays file-listing

我正在使用下面的代码将文件名保存到数组中。我从这里得到了代码save file names to an array 。当我运行这段代码时,它说目录中有 5 个文件(即 count 为 5),但是,只有 3 个。有人可以验证这是否正确,还是我犯了一个严重错误?

#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]);
    }
}

最佳答案

几个月前,我在一个学校项目中问了自己同样的问题。当您使用 dirent 结构并通过访问元素 d_name 列出它们时,它实际上会计算目录加上“.”。和“..”,所以这是正常的。如果您不想将它们作为目录,只需为循环创建一个迭代器变量并添加如下条件:

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

关于c - 列出c目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407021/

相关文章:

c - 找到程序中分配的内存?

c - 扫描随机数的 float ,直到 C 中的新行

c - Visual Studio : Unresolved external symbols after adding new DLL APIs

javascript - 获取 JavaScript 数组中的所有唯一值(删除重复项)

c - main函数返回导致异常

java - 在字符串数组中加载 .text 文件

arrays - PostgreSQL 中两个数组的并集,无需取消嵌套

ruby - 确定规范的 gem 文件列表

javascript - PhantomJS fs.list() 返回错误的长度