C++如何遍历文件夹下的所有文件

来源:AI编程作者:深圳程序员头衔:程序员
导读:本期聚焦于小伙伴创作的《C++如何遍历文件夹下的所有文件》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C++如何遍历文件夹下的所有文件》有用,将其分享出去将是对创作者最好的鼓励。

在C++17之前,遍历文件夹需要依赖操作系统提供的API,比如Windows的FindFirstFile、Linux的opendir等,这些接口不仅平台差异大,使用起来也比较繁琐。C++17正式将filesystem纳入标准库,提供了统一的目录遍历接口,大幅降低了跨平台文件操作的难度。

C++如何遍历文件夹下的所有文件

C++17 filesystem基础准备

使用filesystem前需要包含对应的头文件,并且注意不同编译器的命名空间差异。大部分现代编译器已经完全支持C++17的filesystem,部分旧版本编译器可能需要使用实验性的命名空间。

#include <iostream>
#include <filesystem>
// 对于部分旧版本编译器,可能需要使用 std::experimental::filesystem
// 同时需要链接对应的库,比如GCC需要添加 -lstdc++fs 编译选项
namespace fs = std::filesystem;

基础非递归遍历文件夹

使用directory_iterator可以实现对指定目录的直接子项遍历,不会进入子目录。遍历过程中每个迭代项都是directory_entry对象,可以获取文件的相关属性。

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    // 要遍历的目标文件夹路径,这里使用当前目录作为示例
    fs::path target_dir = "./test_dir";
    // 检查路径是否存在且是目录
    if (!fs::exists(target_dir) || !fs::is_directory(target_dir)) {
        std::cerr << "目标路径不存在或不是目录" << std::endl;
        return 1;
    }
    // 使用directory_iterator遍历目录
    for (const auto& entry : fs::directory_iterator(target_dir)) {
        // 获取文件完整路径
        fs::path file_path = entry.path();
        // 判断是否是普通文件
        if (fs::is_regular_file(entry.status())) {
            std::cout << "普通文件: " << file_path.string() << std::endl;
        } else if (fs::is_directory(entry.status())) {
            std::cout << "子目录: " << file_path.string() << std::endl;
        } else {
            std::cout << "其他类型: " << file_path.string() << std::endl;
        }
    }
    return 0;
}

递归遍历所有子目录文件

如果需要遍历目标目录下的所有子目录中的文件,可以使用recursive_directory_iterator,它会自动递归进入所有子目录进行遍历。

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    fs::path target_dir = "./test_dir";
    if (!fs::exists(target_dir) || !fs::is_directory(target_dir)) {
        std::cerr << "目标路径不存在或不是目录" << std::endl;
        return 1;
    }
    // 使用递归迭代器遍历所有子项
    for (const auto& entry : fs::recursive_directory_iterator(target_dir)) {
        fs::path file_path = entry.path();
        // 只输出普通文件的路径
        if (fs::is_regular_file(entry.status())) {
            std::cout << "文件路径: " << file_path.string() << std::endl;
        }
    }
    return 0;
}

过滤特定类型的文件

实际开发中经常需要只处理特定后缀的文件,比如只遍历所有的txt文件或者cpp文件,可以在遍历过程中添加后缀判断逻辑。

#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;

int main() {
    fs::path target_dir = "./test_dir";
    std::string target_ext = ".cpp"; // 要过滤的目标后缀
    if (!fs::exists(target_dir) || !fs::is_directory(target_dir)) {
        std::cerr << "目标路径不存在或不是目录" << std::endl;
        return 1;
    }
    for (const auto& entry : fs::recursive_directory_iterator(target_dir)) {
        fs::path file_path = entry.path();
        if (fs::is_regular_file(entry.status())) {
            // 获取文件后缀并转为小写比较
            std::string ext = file_path.extension().string();
            // 简单处理后缀大小写问题
            for (char& c : ext) {
                c = tolower(c);
            }
            if (ext == target_ext) {
                std::cout << "目标文件: " << file_path.string() << std::endl;
            }
        }
    }
    return 0;
}

遍历过程中的异常处理

遍历目录时可能会遇到权限不足、路径不存在、文件被占用等异常情况,需要使用异常处理机制保证程序的稳定性。

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    fs::path target_dir = "./test_dir";
    try {
        if (!fs::exists(target_dir)) {
            std::cerr << "路径不存在" << std::endl;
            return 1;
        }
        for (const auto& entry : fs::directory_iterator(target_dir)) {
            try {
                // 尝试获取文件状态,可能触发异常
                fs::file_status status = entry.status();
                if (fs::is_regular_file(status)) {
                    std::cout << "文件: " << entry.path().string() << std::endl;
                }
            } catch (const fs::filesystem_error& e) {
                std::cerr << "处理文件 " << entry.path().string() << " 时出错: " << e.what() << std::endl;
            }
        }
    } catch (const fs::filesystem_error& e) {
        std::cerr << "遍历目录失败: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

两种迭代器的选择建议

directory_iteratorrecursive_directory_iterator的选择需要根据实际需求决定:

  • 如果只需要处理目标目录下的直接子项,不需要进入子目录,优先使用directory_iterator,性能更高
  • 如果需要处理目标目录及所有子目录下的文件,使用recursive_directory_iterator,避免自己实现递归逻辑

另外需要注意,filesystem的路径处理是跨平台的,不需要担心Windows的反斜杠和Linux的正斜杠差异,库会自动处理路径分隔符的转换。

C++17filesystem目录遍历文件遍历修改时间:2026-07-09 09:42:29

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。