C++ 遍历目录


单层遍历目录(无递归):

#include <filesystem>

namespace fs = std::filesystem;

const fs::path pathToShow{ argc >= 2 ? argv[1] : fs::current_path() };

for (const auto& entry : fs::directory_iterator(pathToShow)) {
    const auto filenameStr = entry.path().filename().string();
    if (entry.is_directory()) {
        std::cout << "dir:  " << filenameStr << '\n';
    }
    else if (entry.is_regular_file()) {
        std::cout << "file: " << filenameStr << '\n';
    }
    else
        std::cout << "??    " << filenameStr << '\n';
}

 

递归遍历目录:

for(auto itEntry = fs::recursive_directory_iterator(pathToShow);
         itEntry != fs::recursive_directory_iterator(); 
         ++itEntry ) {
    const auto filenameStr = iterEntry->path().filename().string();
    std::cout << std::setw(iterEntry.depth()*3) << "";
    std::cout << "dir:  " << filenameStr << '\n';
}

可以使用 depth() 方法检查当前的递归层级,这将有助于创建一个带缩进的输出。

 

 

C++17 暴漏了一个 path 类型,可以很方便的获取路径的扩展名,仅仅使用 path::extension() 方法即可,举例如下:

std::filesystem::path("C:\\temp\\hello.txt").extension();

支持的编译器有

FeatureGCCClangMSVC
Filesystem 11.0 7.0 VS 2017 15.7

GCC9 部分支持 C++17 特性,一直到 GCC11 才完全支持C++17

posted on 2023-02-27 19:59  阳光雨露&  阅读(348)  评论(0编辑  收藏  举报

导航