C++中遍历文件夹推荐使用C++17的std::filesystem,跨平台且简洁;Windows可用Win32 API如FindFirstFile;Linux/Unix可用dirent.h;旧环境需条件编译适配不同系统。

在C++中遍历文件夹下的所有文件,有多种方式实现,取决于你使用的操作系统和标准库支持程度。下面介绍几种常见且实用的方法。
使用C++17标准库filesystem
如果你的编译器支持C++17,推荐使用std::filesystem,它提供了简洁、跨平台的目录遍历接口。示例代码:
#include#include namespace fs = std::filesystem;
void traverse_directory(const std::string& path) { for (const auto& entry : fs::directory_iterator(path)) { std::cout << entry.path() << std::endl; } }
int main() { traverse_directory("./test_folder"); return 0; }
这个方法可以轻松递归遍历子目录:
立即学习“C++免费学习笔记(深入)”;
for (const auto& entry : fs::recursive_directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
编译时需要链接C++17标准:
g++ -std=c++17 your_file.cpp -o your_program
Windows平台使用Win32 API
在Windows环境下,可以使用FindFirstFile和FindNextFile函数进行目录遍历。示例代码:
#include#include void traverse_windows(const std::string& path) { WIN32_FIND_DATAA ffd; HANDLE hFind = FindFirstFileA((path + "\*").c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) { std::cout << "无法打开目录" << std::endl; return; } do { if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) { std::cout << path + "\\" + ffd.cFileName << std::endl; } } while (FindNextFileA(hFind, &ffd) != 0); FindClose(hFind);}
这种方式兼容老版本编译器,但仅限Windows平台。
Linux/Unix使用dirent.h
在Linux或macOS系统中,可以使用POSIX标准的dirent.h头文件来遍历目录。示例代码:
#include#include #include void traverse_linux(const std::string& path) { DIR dir; struct dirent ent;
if ((dir = opendir(path.c_str())) != nullptr) { while ((ent = readdir(dir)) != nullptr) { if (std::string(ent->d_name) != "." && std::string(ent->d_name) != "..") { std::cout << path + "/" + ent->d_name << std::endl; } } closedir(dir); } else { std::cout << "无法打开目录" << std::endl; }}
注意:该方法不支持递归自动进入子目录,需自行判断并递归调用。
跨平台封装建议
如果项目需要跨平台运行,建议优先使用C++17的filesystem。如果不支持C++17,可封装条件编译逻辑:
- 检测编译环境,选择对应API
- 统一返回路径列表或通过回调函数处理每个文件
- 过滤隐藏文件或特定扩展名时,在循环中添加判断即可
基本上就这些。现代C++推荐用
std::filesystem,简洁安全;旧环境则根据平台选择Win32或dirent方案。只要注意路径分隔符和权限问题,遍历目录并不复杂。











