使用C++17的std::filesystem可跨平台遍历文件夹,支持常规和递归遍历,Windows可用Win32 API,Linux可用dirent.h,推荐优先使用std::filesystem。

在C++中遍历一个文件夹下的所有文件,可以使用不同操作系统提供的API,也可以借助标准库或第三方库来实现跨平台操作。以下是几种常见的实现方式。
使用C++17的std::filesystem(推荐)
C++17引入了std::filesystem库,提供了便捷的目录遍历功能,跨平台且易于使用。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include int main() { std::string path = "./test_folder"; // 替换为你要遍历的路径
try { for (const auto& entry : std::filesystem::directory_iterator(path)) { if (entry.is_regular_file()) { std::cout << "文件: " << entry.path().filename() << '\n'; } else if (entry.is_directory()) { std::cout << "目录: " << entry.path().filename() << '\n'; } } } catch (const std::exception& e) { std::cerr << "错误: " << e.what() << '\n'; } return 0;} 编译时需要启用C++17支持:
g++ -std=c++17 your_file.cpp -o your_program递归遍历子目录
如果需要递归访问所有子目录中的文件,可以使用std::filesystem::recursive_directory_iterator。示例:
for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) { if (entry.is_regular_file()) { std::cout << "发现文件: " << entry.path().string() << '\n'; } }Windows平台使用Win32 API
在Windows环境下,可以使用FindFirstFile和FindNextFile函数遍历目录。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include void listFilesWin32(const std::string& path) { WIN32_FIND_DATAA data; std::string searchPath = path + "\*"; HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);
if (hFind == INVALID_HANDLE_VALUE) { std::cerr << "无法打开目录\n"; return; } do { std::string name = data.cFileName; if (name == "." || name == "..") continue; if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::cout << "目录: " << name << '\n'; } else { std::cout << "文件: " << name << '\n'; } } while (FindNextFileA(hFind, &data)); FindClose(hFind);}
Linux/Unix使用dirent.h
在Linux系统中,可以使用头文件中的函数进行目录操作。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include #include void listFilesLinux(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; if (ent->d_type == DT_DIR) { std::cout << "目录: " << name << '\n'; } else { std::cout << "文件: " << name << '\n'; } } closedir(dir); } else { std::cerr << "无法打开目录\n"; }}
总结建议:
- 推荐使用C++17的
std::filesystem,简洁、安全、跨平台。- 若项目不支持C++17,可根据平台选择Win32 API或
dirent.h。- 注意处理异常和权限问题,避免程序崩溃。
基本上就这些方法,按需选择即可。











