
在C++中遍历文件夹下的所有文件和子文件夹,可以使用不同平台的API或跨平台库。下面介绍几种常见实现方式。
使用C++17标准库 filesystem
C++17引入了 std::filesystem,提供了简洁的目录遍历接口,推荐优先使用。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include编译时需启用C++17支持,例如g++添加参数:-std=c++17,并且某些编译器(如GCC)需要链接 -lstdc++fs。#include namespace fs = std::filesystem; void traverse(const fs::path& path) { for (const auto& entry : fs::directory_iterator(path)) { std::cout << entry.path() << "\n"; if (entry.is_directory()) { traverse(entry.path()); // 递归进入子目录 } } } int main() { fs::path dir = "."; // 当前目录 traverse(dir); return 0; }
Windows平台 API 实现
在Windows下可使用 Win32 FindFirstFile / FindNextFile API。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include该方法仅适用于Windows系统,无需额外库,但不具备跨平台性。#include void traverseWindows(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; do { std::string name = data.cFileName; if (name == "." || name == "..") continue; std::string fullPath = path + "\\" + name; std::cout << fullPath << "\n"; if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { traverseWindows(fullPath); // 递归 } } while (FindNextFileA(hFind, &data)); FindClose(hFind); }
使用第三方库:Boost.Filesystem
在C++17不可用时,Boost.Filesystem 是一个成熟的选择。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include需安装Boost并正确配置头文件和库路径。#include namespace fs = boost::filesystem; void traverseBoost(const fs::path& path) { if (!fs::exists(path)) return; for (const auto& entry : fs::directory_iterator(path)) { std::cout << entry.path() << "\n"; if (fs::is_directory(entry.status())) { traverseBoost(entry.path()); } } }
注意事项与建议
- 检查目录是否存在,避免运行时错误
- 处理隐藏文件、符号链接等特殊情况
- 注意路径分隔符在不同系统的差异(/ vs \\)
- 递归深度较大时注意栈溢出风险,可改用栈结构迭代实现











