如何使用现代C ++获取特定路径下目录/文件和子目录的向量?
答案 0 :(得分:0)
与 std::filesystem
..!
#if __cplusplus < 201703L// If the version of C++ is less than 17
// It was still in the experimental:: namespace
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
std::vector<fs::path> geteverything(const fs::path &path)
{
std::vector<fs::path> dirs;
for (const auto & entry : fs::directory_iterator(path))
{
dirs.push_back(entry);
if (fs::is_directory(entry))
{
auto subdirs = geteverything(entry);
dirs.insert(dirs.end(), subdirs.begin(), subdirs.end());
}
}
return dirs;
}
测试
// Change this to the absolute/relative path you'd like to fetch.
std::string path = "C:/Windows/Temp";
int main()
{
std::cout << "fetching all directories and files in : " << path << " ...\n";
auto list = geteverything(path);
for (const auto &path : list)
std::cout << path << "\n";
return 0;
}