c_cpp 迭代目录

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 迭代目录相关的知识,希望对你有一定的参考价值。

// Experimental
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

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


// C++17 and above
#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';
}


// Recursive iterator
void DisplayDirectoryTree(const fs::path& pathToScan, int level = 0) {
    for (const auto& entry : fs::directory_iterator(pathToScan)) {
        const auto filenameStr = entry.path().filename().string();
        if (entry.is_directory()) {
            std::cout << std::setw(level * 3) << "" << filenameStr << '\n';
            DisplayDirectoryTree(entry, level + 1);
        }
        else if (entry.is_regular_file()) {
            std::cout << std::setw(level * 3) << "" << filenameStr
                << ", size " << entry.file_size() << " bytes\n";
        }
        else
            std::cout << std::setw(level * 3) << "" << " [?]" << filenameStr << '\n';
    }
}

以上是关于c_cpp 迭代目录的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 迭代DFS

c_cpp 擦除迭代器

c_cpp 反向链表,迭代,递归

c_cpp 迭代二进制搜索树

c_cpp C ++ - const迭代器

c_cpp 合并两个排序列表,递归和迭代