【问题标题】:Need To Eliminate Directories From File Listing in C需要从 C 中的文件列表中删除目录
【发布时间】:2011-05-15 03:25:12
【问题描述】:

我有一个问题,我需要获取目录中的文件列表。使用这个previous StackOverflow question 作为基础,我目前有这个代码:

void get_files(int maxfiles) {
    int count = 0;
    DIR *dir;
    struct dirent *ent;
    dir = opendir(DIRECTORY);
    if (dir != NULL) {

        /* get all the files and directories within directory */
        while ((ent = readdir(dir)) != NULL) {
            if (count++ > maxfiles) break;

            printf("%s\n", ent->d_name);
        }
        closedir(dir);
    } else {
        /* could not open directory */
        printf("ERROR: Could not open directory");
        exit(EXIT_FAILURE);
    }
}

现在它几乎完全按照我想要的方式工作,但问题是它还列出了 directories 与他的文件,我只想要文件条目。我可以做一个简单的修改来做到这一点吗?

【问题讨论】:

    标签: c unix file


    【解决方案1】:

    如果您的struct dirent 包含非标准但广泛可用的d_type 成员,您可以使用它来过滤目录。值得选择使用它,并且只在不使用它的系统上回退到 stat,因为使用 d_type 而不是 stat 可能会使您的目录列表速度提高数十或数百倍。

    【讨论】:

      【解决方案2】:

      您可以使用类似的代码过滤目录 this one

      【讨论】:

        【解决方案3】:

        POSIX 定义了fstat,可用于检查文件是否为目录。它还有一个宏来简化检查。
        http://linux.die.net/man/2/fstat
        请注意,对于 Windows,您可能必须在此处使用 Windows API。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-26
          相关资源
          最近更新 更多