简体   繁体   English

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

[英]Get all directories/files and sub-directories in a specific path using pure c++ (cross-platform)

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

Using a recursive function with std::filesystem ..! 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;
}

Test 测试

// 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM