使用纯c ++(跨平台)获取特定路径中的所有目录/文件和子目录

时间:2019-02-20 10:35:36

标签: c++ cross-platform

如何使用现代C ++获取特定路径下目录/文件和子目录的向量?

1 个答案:

答案 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;
}