代码之家  ›  专栏  ›  技术社区  ›  Ash

需要从C中的文件列表中删除目录

  •  0
  • Ash  · 技术社区  · 14 年前

    我有一个问题,我需要得到一个目录中的文件列表。使用此 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);
        }
    }
    

    现在它的工作方式和我想要的差不多,但问题是它也列出了 目录 我只需要文件条目。我能做一个简单的修改吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   Community CDub    7 年前

    您可以使用类似于 this one

        2
  •  2
  •   buddhabrot    14 年前

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

        3
  •  0
  •   R.. GitHub STOP HELPING ICE    14 年前

    如果你 struct dirent 包含非标准但广泛可用的 d_type 成员,您可以使用它筛选出目录。值得有选择地使用它,而且只能退回到 stat 在不存在的系统上,因为使用 DY-型 而不是stat,可能会使目录列表的速度快几十倍或数百倍。