推荐使用C++17的std::filesystem进行跨平台目录遍历,语法简洁且支持递归操作;2. Windows可用Win32 API如FindFirstFile实现高效遍历;3. Linux系统可采用dirent.h结合readdir和stat函数处理;4. 遍历时需跳过"."和".."防止无限递归,注意路径分隔符差异及权限异常处理。

在C++中遍历文件夹下的所有文件,可以使用不同平台的API或跨平台库。下面介绍几种常见实现方式,帮助你高效完成目录遍历任务。
使用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() << "\n";
// 判断是否为子目录,可递归进入 if (entry.is_directory()) { traverse_directory(entry.path().string()); } }}
立即学习“C++免费学习笔记(深入)”;
int main() { std::string folder = "C:/your/folder/path"; // Windows路径或Linux路径 traverse_directory(folder); return 0; }
编译时需启用C++17支持:
g++ -std=c++17 your_file.cpp -o your_programWindows平台使用Win32 API
在Windows环境下,可通过FindFirstFile和FindNextFile实现高效遍历。示例代码:
#include#include void traverse_win32(const std::string& path) { WIN32_FIND_DATAA data; std::string search_path = path + "\*";
HANDLE hFind = FindFirstFileA(search_path.c_str(), &data); if (hFind == INVALID_HANDLE_VALUE) return; do { std::string name = data.cFileName; if (name == "." || name == "..") continue; std::string full_path = path + "\\" + name; std::cout << full_path << "\n"; if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { traverse_win32(full_path); // 递归进入子目录 } } while (FindNextFileA(hFind, &data)); FindClose(hFind);}
此方法兼容老版本C++标准,但仅限Windows使用。
Linux/Unix使用dirent.h
在Linux系统中,常用dirent.h头文件提供的接口进行目录操作。示例代码:
#include#include #include void traverse_dirent(const std::string& path) { DIR dir; struct dirent ent;
if ((dir = opendir(path.c_str())) != nullptr) { while ((ent = readdir(dir)) != nullptr) { std::string name = ent->d_name; if (name == "." || name == "..") continue; std::string full_path = path + "/" + name; std::cout << full_path << "\n"; // 注意:此处无法直接判断是否为目录(某些系统需stat) // 可结合stat函数进一步判断 } closedir(dir); }}
若需判断文件类型,建议配合
stat()函数使用。跨平台建议与注意事项
- 优先使用C++17的
std::filesystem,语法清晰且跨平台。- 注意路径分隔符差异:Windows用
\\,Linux用/,可用fs::path自动处理。- 遍历时跳过
.和..目录,避免无限递归。- 对大目录遍历注意性能,避免频繁I/O操作影响效率。
- 权限不足或路径不存在时做好异常处理(如捕获filesystem_error)。
基本上就这些。选择合适的方法取决于你的编译器支持和目标平台。









