C++中遍历目录推荐使用C++17的<filesystem>,如for (const auto& entry : fs::directory_iterator(path)),可判断is_regular_file()过滤文件,支持递归遍历;Windows可用FindFirstFile/FindNextFile,Linux/Unix用opendir/readdir,跨平台可封装或使用Boost.Filesystem。

在C++中遍历目录下的所有文件,有多种实现方式,具体取决于操作系统和使用的标准库或第三方库。以下是几种常用且实用的方法。
使用 <filesystem>(C++17 及以上)
从 C++17 开始,标准库引入了 <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 listFiles(const std::string& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "\n";
}
}</p>如果只想列出文件(排除子目录),可以加判断:
if (entry.is_regular_file()) {
std::cout << entry.path().filename() << "\n";
}
支持递归遍历:
for (const auto& entry : fs::recursive_directory_iterator(path)) {
// 处理每个条目
}
Windows 平台:使用 Win32 API
在 Windows 上,可以使用 FindFirstFile 和 FindNextFile 函数。
#include <windows.h>
#include <iostream>
<p>void listFilesWin32(const std::string& dir) {
WIN32_FIND_DATA data;
HANDLE hFind = FindFirstFile((dir + "\*").c_str(), &data);</p><pre class='brush:php;toolbar:false;'>if (hFind == INVALID_HANDLE_VALUE) return;
do {
if (data.cFileName[0] != '.') { // 忽略 . 和 ..
std::cout << data.cFileName << "\n";
}
} while (FindNextFile(hFind, &data));
FindClose(hFind);}
该方法仅适用于 Windows,但性能良好且控制精细。
Linux/Unix:使用 dirent.h
在类 Unix 系统中,可使用 <dirent.h> 提供的函数进行目录遍历。
#include <dirent.h>
#include <iostream>
#include <string>
<p>void listFilesUnix(const std::string& path) {
DIR* dir = opendir(path.c_str());
if (!dir) return;</p><pre class='brush:php;toolbar:false;'>struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
std::cout << entry->d_name << "\n";
}
}
closedir(dir);}
注意:不同系统的 d_type 支持可能不一致,若需判断是否为文件或目录,建议配合 stat() 使用。
跨平台兼容建议
若项目不能使用 C++17,又需要跨平台,可考虑以下方案:
- 封装 Win32 API 和 dirent.h,通过宏判断平台
- 使用第三方库如 Boost.Filesystem(功能类似 std::filesystem,更早可用)
- 优先升级编译器以支持 C++17 的 <filesystem>
Boost 示例:
#include <boost/filesystem.hpp> // 用法与 std::filesystem 基本一致
基本上就这些。现代 C++ 推荐使用 <filesystem>,简洁安全,跨平台能力强。旧项目可根据平台选择原生 API 实现。关键是处理好隐藏文件(.开头)和递归需求。










