如何从我的 C 或 C++ 代码中确定目录中的文件列表?
我不允许执行 ls
命令并从我的程序中解析结果。
最佳答案
2017 年更新:
在 C++17 中,现在有一种列出文件系统文件的官方方法:std::filesystem
。 Shreevardhan 有一个很好的回答下面是这个源代码:
#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 中可作为标准头文件使用,也可通过 compatibility layer created by Toni Ronkko 用于 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!)。
关于c++ - 如何使用 C 或 C++ 获取目录中的文件列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/612097/