如何使用 C 或 C++ 获取目录中的文件列表?
如何从我的 C 或 C++ 代码中确定目录中的文件列表?
How can I determine the list of files in a directory from inside my C or C++ code?
我不允许执行 ls
命令并从我的程序中解析结果.
I'm not allowed to execute the ls
command and parse the results from within my program.
2017 年更新:
在 C++17 中,现在有一种官方的方式来列出文件系统的文件:std::filesystem
.下面的 Shreevardhan 提供了一个很好的答案,其中包含此源代码(此代码可能会抛出):
In C++17 there is now an official way to list files of your file system: std::filesystem
. There is an excellent answer from Shreevardhan below with this source code (This code may throw):
#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 创建的 兼容层 用于 Windows.
In small and simple tasks I do not use boost, I use dirent.h. It is available as a standard header in UNIX, and also available for Windows via a compatibility layer created by Toni Ronkko.
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
", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
它只是一个很小的头文件,可以完成您需要的大部分简单工作,而无需使用像 boost 这样的基于模板的大型方法(没有冒犯,我喜欢 boost!).
It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost(no offence, I like boost!).