
在C++中遍历一个文件夹下的所有文件,有多种实现方式,取决于你使用的平台和标准库。下面介绍几种常用的方法,包括跨平台和特定平台的实现。
使用 C++17 的 std::filesystem(推荐)
从 C++17 开始,标准库提供了 std::filesystem 模块,可以方便地遍历目录,跨平台且语法简洁。需要包含头文件 ,并启用 C++17 支持。
示例代码:
#include#include namespace fs = std::filesystem;
立即学习“C++免费学习笔记(深入)”;
int main() { std::string path = "./test_folder"; // 替换为你的目录路径
try { for (const auto& entry : fs::directory_iterator(path)) { std::cout << entry.path() << std::endl; } } catch (const fs::filesystem_error& ex) { std::cerr << "Error accessing directory: " << ex.what() << std::endl; } return 0;}
如果只想遍历文件(排除子目录),可以加判断:
for (const auto& entry : fs::directory_iterator(path)) { if (entry.is_regular_file()) { std::cout << "File: " << entry.path().filename() << std::endl; } }递归遍历子目录使用 fs::recursive_directory_iterator:
for (const auto& entry : fs::recursive_directory_iterator(path)) { if (entry.is_regular_file()) { std::cout << "Found file: " << entry.path() << std::endl; } }Windows 平台:使用 Win32 API
在 Windows 上,可以使用 FindFirstFile 和 FindNextFile 函数。#include#include int main() { WIN32_FIND_DATA data; HANDLE hFind = FindFirstFile(".\.", &data); // 当前目录下所有文件
if (hFind == INVALID_HANDLE_VALUE) { std::cerr << "Cannot open directory." << std::endl; return 1; } do { if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::cout << "[DIR] " << data.cFileName << std::endl; } else { std::cout << "[FILE] " << data.cFileName << std::endl; } } while (FindNextFile(hFind, &data)); FindClose(hFind); return 0;}
注意:这种方式不递归,仅列出当前目录内容。
Linux/Unix 平台:使用 dirent.h
在类 Unix 系统中,可以使用提供的函数。 #include#include #include int main() { DIR dir; struct dirent ent; std::string path = "./";
if ((dir = opendir(path.c_str())) != nullptr) { while ((ent = readdir(dir)) != nullptr) { if (ent->d_type == DT_REG) { std::cout << "[FILE] " << ent->d_name << std::endl; } else if (ent->d_type == DT_DIR) { std::cout << "[DIR] " << ent->d_name << std::endl; } } closedir(dir); } else { std::cerr << "Could not open directory." << std::endl; return 1; } return 0;}
跨平台兼容建议
如果你的项目支持 C++17,强烈推荐使用 std::filesystem,它统一了不同系统的差异,代码清晰易维护。如果不支持 C++17,可考虑:
- 使用第三方库如 Boost.Filesystem(与 std::filesystem 接口相似)
- 封装平台相关代码,用宏区分 Windows 和 Unix 实现
基本上就这些方法。现代 C++ 优先选 filesystem,老项目再考虑平台 API。编译时记得开启 -std=c++17,并链接 stdc++fs(某些旧编译器需要)。











