首页 > 后端开发 > C++ > 正文

c++中如何遍历文件夹下的所有文件_C++递归遍历目录文件实现方法

裘德小鎮的故事
发布: 2025-09-21 16:24:01
原创
537人浏览过
c++kquote>使用C++17 filesystem可跨平台递归遍历目录,推荐此方法;Windows可用FindFirstFile API,Linux/Unix可用dirent.h,注意路径分隔符与编码处理。

c++中如何遍历文件夹下的所有文件_c++递归遍历目录文件实现方法

在C++中遍历文件夹下的所有文件,尤其是包含子目录的递归遍历,可以通过不同平台的API或跨平台库来实现。下面分别介绍使用Windows API、POSIX(Linux/macOS)以及现代C++17标准中的

<filesystem>
登录后复制
方法。

使用C++17 filesystem(推荐)

C++17引入了
<filesystem>
登录后复制
头文件,提供了跨平台的文件系统操作支持,是目前最简洁、安全的方式。

示例代码:

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

void traverse(const fs::path& path) {
    for (const auto& entry : fs::recursive_directory_iterator(path)) {
        if (entry.is_regular_file()) {
            std::cout << "File: " << entry.path().string() << ' ';
        } else if (entry.is_directory()) {
            std::cout << "Dir: " << entry.path().string() << ' ';
        }
    }
}

int main() {
    traverse("C:/example"); // 替换为你的路径
    return 0;
}

编译时需启用C++17支持,例如g++:
g++ -std=c++17 main.cpp -o main

Windows平台:使用Win32 API

在Windows下可使用
FindFirstFile
登录后复制
FindNextFile
登录后复制
进行递归遍历。

示例代码:

#include <iostream>
#include <windows.h>
#include <string>

void traverse_win32(const std::string& path) {
    std::string searchPath = path + "*";
    WIN32_FIND_DATAA data;
    HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);

    if (hFind == INVALID_HANDLE_VALUE) return;

立即学习C++免费学习笔记(深入)”;

笔目鱼英文论文写作器
笔目鱼英文论文写作器

写高质量英文论文,就用笔目鱼

笔目鱼英文论文写作器 87
查看详情 笔目鱼英文论文写作器

    do {
        if (std::string(data.cFileName) == "." || std::string(data.cFileName) == "..")
            continue;

        std::string fullPath = path + "" + data.cFileName;

        if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            std::cout << "Dir: " << fullPath << ' ';
            traverse_win32(fullPath); // 递归进入子目录
        } else {
            std::cout << "File: " << fullPath << ' ';
        }
    } while (FindNextFileA(hFind, &data));

    FindClose(hFind);
}

int main() {
    traverse_win32("C:example");
    return 0;
}

Linux/Unix:使用dirent.h

在POSIX系统中,可以使用
<dirent.h>
登录后复制
<sys/stat.h>
登录后复制
进行递归遍历。

示例代码:

#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>

bool is_directory(const std::string& path) {
    struct stat st;
    return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}

void traverse_linux(const std::string& path) {
    DIR* dir = opendir(path.c_str());
    if (!dir) return;

    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
        std::string name = entry->d_name;
        if (name == "." || name == "..") continue;

        std::string fullPath = path + "/" + name;

        if (is_directory(fullPath)) {
            std::cout << "Dir: " << fullPath << ' ';
            traverse_linux(fullPath);
        } else {
            std::cout << "File: " << fullPath << ' ';
        }
    }

    closedir(dir);
}

int main() {
    traverse_linux("/home/user/example");
    return 0;
}

注意事项与建议

- 推荐优先使用C++17的
std::filesystem
登录后复制
,代码简洁且跨平台。
- 注意路径分隔符:Windows用反斜杠
\
登录后复制
,Linux用
/
登录后复制
,可用条件编译或统一使用
/
登录后复制
(多数系统支持)。
- 递归深度过大可能导致溢出,可改用栈结构模拟递归。
- 处理中文路径时确保编码一致,Windows建议使用宽字符版本API(如FindFirstFileW)。

基本上就这些,选择合适的方法取决于你的目标平台和C++标准支持情况。

以上就是c++++中如何遍历文件夹下的所有文件_C++递归遍历目录文件实现方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号