如何使用 C 或 C 获取目录中的文件列表?

新手上路,请多包涵

如何从我的 C 或 C++ 代码中确定目录中的文件列表?

我不允许执行 ls 命令并从我的程序中解析结果。

原文由 samoz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 990
2 个回答

2017 年更新

在 C++17 中,现在有一种列出文件系统文件的官方方法: std::filesystemShreevardhan 下面的源代码给出了一个很好的答案:

>  #include <string>
> #include <iostream>
> #include <filesystem>
> namespace fs = std::filesystem;
>
> int main()
> {
>     std::string path = "/path/to/directory";
>     for (const auto & entry : fs::directory_iterator(path))
>         std::cout << entry.path() << std::endl;
> }
>
> ```

**老答案:**

在不使用 boost 的小而简单的任务中,我使用 **dirent.h** 。它可以作为 UNIX 中的标准头文件使用,也可以 [通过 Toni Ronkko 创建的兼容层](https://github.com/tronkko/dirent) 用于 Windows。

DIR *dir; struct dirent ent; if ((dir = opendir (“c:\src\”)) != NULL) { / print all the files and directories within directory / while ((ent = readdir (dir)) != NULL) { printf (“%s\n”, ent->d_name); } closedir (dir); } else { / could not open directory */ perror (“”); return EXIT_FAILURE; }

”`

它只是一个小头文件,无需使用诸如 boost 之类的基于模板的大方法即可完成您需要的大部分简单工作(无意冒犯,我喜欢 boost!)。

原文由 Peter Parker 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需在 Linux 中使用以下 ASCI C 样式代码

#include <bits/stdc++.h>
#include <dirent.h>
using namespace std;

int main(){
    DIR *dpdf;
    struct dirent *epdf;
    dpdf = opendir("./");

    if (dpdf != NULL){
    while (epdf = readdir(dpdf)){
        cout << epdf->d_name << std::endl;
    }
    }
    closedir(dpdf);
    return 0;
}

希望这可以帮助!

原文由 Vaibhav Pallod 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题