スポンサーリンク

std::filesystemで取得可能なディレクトリツリーを自作構造体に格納

std::filesystemを使えばディレクトリ構造を辿ることができるが、これを自作した構造体に格納する。

#include <iostream>

#include <vector>
#include <string>
#include <filesystem>

// SetConsoleOutputCP のために必要
#include <windows.h>

enum class FileType {
    Ignore,
    Directory,
    File
};

struct DirTree {
    std::string name;
    FileType type;
    std::vector<DirTree> children;
    DirTree(const std::string& name, const FileType type) : name(name), type(type){}
};

// ディレクトリツリーを構築する関数
DirTree buildDirTree(const std::filesystem::path& path) {

    std::string name = path.filename().string();
    FileType type = std::filesystem::is_directory(path) ? FileType::Directory : FileType::File;
    DirTree node(name, type);

    if (type == FileType::Directory) {
        for (const auto& entry : std::filesystem::directory_iterator(path)) {
            node.children.push_back(buildDirTree(entry.path()));
        }
    }

    return node;
}
// ファイルツリーを表示
void printTree(const DirTree& tree, int depth = 0) {

    auto to_string = [](const FileType type) {
        switch (type) {
        case FileType::Ignore: return "*";
        case FileType::Directory: return "[DIR]";
        case FileType::File: return "[FILE]";
        }
        return "Unknown";
    };

    std::string indent(depth * 2, ' ');
    std::cout << indent << to_string(tree.type) << tree.name << "\n";
    for (const auto& child : tree.children) {
        printTree(child, depth + 1);
    }
}

int main()
{

    // windowsのコンソールでUTF-8を表示するために必要
    SetConsoleOutputCP(CP_UTF8);

    std::string path = "C:/tmp/ConsoleApplication2/";
    DirTree root = buildDirTree(path);
    // ファイルのリストをツリー構造に変換
    printTree(root);

}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)


この記事のトラックバックURL: