UPDATE 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;
}
Old Answer:个
在小而简单的任务中,我不使用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!).