C++17遍历目录

类别说明
directory_iterator只遍历目录的当前层级
recursive_directory_iterator递归遍历所有子目录
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    // 设置要遍历的目录,可以从命令行参数获取或默认使用当前目录
    fs::path root_path = (argc > 1) ? fs::path(argv[1]) : fs::current_path();

    try {
        if (!fs::exists(root_path)) {
            std::cerr << "路径不存在: " << root_path << std::endl;
            return 1;
        }

        std::cout << "遍历目录: " << root_path << std::endl;

        for (const auto& entry : fs::recursive_directory_iterator(root_path)) {
            std::cout << entry.path();

            if (entry.is_directory()) {
                std::cout << " [目录]";
            }
            else if (entry.is_regular_file()) {
                std::cout << " [普通文件]";
            }
            else if (entry.is_symlink()) {
                std::cout << " [符号链接]";
            }
            else {
                std::cout << " [其他]";
            }

            std::cout << std::endl;
        }
    }
    catch (const fs::filesystem_error& e) {
        std::cerr << "文件系统错误: " << e.what() << std::endl;
    }

    return 0;
}

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    // 获取要遍历的目录路径
    fs::path dir_path = (argc > 1) ? fs::path(argv[1]) : fs::current_path();

    try {
        if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
            std::cerr << "路径无效或不是目录: " << dir_path << std::endl;
            return 1;
        }

        std::cout << "遍历目录: " << dir_path << std::endl;

        for (const auto& entry : fs::directory_iterator(dir_path)) {
            std::cout << entry.path();

            if (entry.is_directory()) {
                std::cout << " [目录]";
            } else if (entry.is_regular_file()) {
                std::cout << " [普通文件]";
            } else if (entry.is_symlink()) {
                std::cout << " [符号链接]";
            } else {
                std::cout << " [其他]";
            }

            std::cout << std::endl;
        }
    } catch (const fs::filesystem_error& e) {
        std::cerr << "文件系统错误: " << e.what() << std::endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值