推荐使用C++17的std::filesystem遍历文件夹,跨平台且简洁;不支持时可选Win32 API或POSIX opendir方法。

在C++中遍历文件夹中的所有文件,有多种方式,取决于你使用的平台和标准库版本。下面介绍几种常见且实用的方法。
使用 C++17 的 std::filesystem(推荐)
从 C++17 开始,std::filesystem 成为标准库的一部分,提供了跨平台的文件系统操作支持,遍历文件夹变得非常简单。
示例代码:
#include <iostream>
#include <filesystem>
<p>namespace fs = std::filesystem;</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><p>void traverse_directory(const std::string& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "
";
}
}</p><p>int main() {
traverse_directory("C:/your/folder/path");
return 0;
}</p>说明:
- 使用 fs::directory_iterator 遍历指定目录下的所有条目。
- 支持判断是文件还是目录:
entry.is_regular_file()、entry.is_directory()。 - 如需递归遍历子目录,可使用 fs::recursive_directory_iterator。
跨平台兼容性与编译设置
要使用 std::filesystem,注意以下几点:
- 编译器需支持 C++17 或更高版本。
- GCC 8+、Clang 7+、MSVC 2017+ 支持较好。
- 编译时添加 -std=c++17 参数。
- 某些系统(如 Linux)可能需要链接 stdc++fs 库(旧版本),但现代编译器通常不再需要。
Windows 平台使用 Win32 API
在不支持 C++17 的旧项目中,Windows 下可以使用 FindFirstFile 和 FindNextFile。
#include <iostream>
#include <windows.h>
<p>void traverse_win32(const std::string& path) {
WIN32_FIND_DATAA data;
std::string searchPath = path + "*";</p><pre class='brush:php;toolbar:false;'>HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
std::cout << (path + "\" + data.cFileName) << "
";
} while (FindNextFileA(hFind, &data));
FindClose(hFind);}
说明:
- 该方法仅适用于 Windows 系统。
- 需要处理 . 和 .. 目录(可通过判断跳过)。
- 若需递归进入子目录,检查
data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY。
Linux/Unix 使用 opendir / readdir
在类 Unix 系统中,可使用 <dirent.h> 提供的函数。
#include <iostream>
#include <dirent.h>
<p>void traverse_unix(const std::string& path) {
DIR<em> dir;
struct dirent</em> ent;</p><pre class='brush:php;toolbar:false;'>if ((dir = opendir(path.c_str())) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
std::cout << path + "/" + ent->d_name << "
";
}
closedir(dir);
}}
说明:
- 此方法适用于 Linux、macOS 等系统。
- 同样需要过滤 . 和 .. 条目。
- 非跨平台,移植性差。
基本上就这些。现代 C++ 推荐优先使用 std::filesystem,简洁、安全、跨平台。旧项目可根据平台选择 Win32 或 POSIX 方法。关键在于根据编译环境和目标平台合理选型。











