c++17起用std::filesystem::recursive_directory_iterator最省心,需启用-std=c++17、包含头文件、检查路径存在性,并注意符号链接默认不跟进。

用 std::filesystem::recursive_directory_iterator 最省心
C++17 起,标准库原生支持遍历目录,不用依赖 Boost 或系统 API。只要编译器支持 C++17(GCC 8+、Clang 7+、MSVC 2017 Update 5+),开个开关就能用。
常见错误是忘了加编译选项:-std=c++17(GCC/Clang)或 /std:c++17(MSVC),否则会报 ‘filesystem’ is not a member of ‘std’。
实操建议:
- 头文件必须写
#include <filesystem></filesystem>,注意不是<experimental></experimental> - 命名空间要用
std::filesystem,别漏掉filesystem - 路径传入
recursive_directory_iterator前,最好先用std::filesystem::exists()和std::filesystem::is_directory()检查,避免抛std::filesystem::filesystem_error - 迭代器默认跳过符号链接指向的目标(即不递归进软链目录),如需跟进,得传
std::filesystem::directory_options::follow_directory_symlink
for (const auto& entry : std::filesystem::recursive_directory_iterator("src")) {
if (entry.is_regular_file()) {
std::cout
<h3>Windows 下用 <code>FindFirstFileW</code> + <code>FindNextFileW</code> 是兼容性兜底方案</h3>
<p>如果项目必须跑在老旧 MSVC(比如 VS2015)或需要精确控制遍历行为(比如跳过某些子目录、处理长路径失败),就得调 Windows API。它不依赖标准库版本,但只适用于 Windows。</p>
<p>容易踩的坑集中在字符编码和路径长度:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/shouce/1510" title="C函数速查手册(CHM版)"><img
src="https://img.php.cn/upload/manual/000/000/001/5d6de31fedca2993.png" alt="C函数速查手册(CHM版)" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/shouce/1510" title="C函数速查手册(CHM版)" class="overflowclass">C函数速查手册(CHM版)</a>
<p class="overflowclass">C函数速查手册(CHM版)</p>
</div>
<a rel="nofollow" href="/xiazai/shouce/1510" title="C函数速查手册(CHM版)" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
- 必须用宽字符版本(
W结尾),传入L"*.cpp"这类const wchar_t*,否则中文路径直接乱码或失败 -
FindFirstFileW的路径参数不能是纯目录名(如L"logs"),得带通配符,例如L"logs\*",否则返回无效句柄 - 单次
FindNextFileW不递归,要自己用栈或队列实现深度/广度优先遍历;手动处理子目录时,记得过滤掉L"."和L".." - 遇到路径超 260 字符,默认会失败,需在 manifest 中启用 long path support,或在路径前加
L"\\?\C:\..."前缀
Linux/macOS 下用 opendir/readdir 需手动递归且注意 errno
POSIX 方案最通用,glibc、musl、macOS libc 都支持,但 C++ 里得混用 C 风格 API,没有 RAII 自动清理,容易泄漏 DIR* 指针。
关键点不在“怎么打开”,而在“怎么不出错”:
-
readdir返回NULL不一定代表结束——可能是内存不足或 I/O 错误,得结合errno判断;errno == 0才是正常遍历完 - 子目录递归前,必须用
stat()确认st_mode & S_IFDIR,不能只看文件名后缀或硬编码判断 - 路径拼接容易崩:用
snprintf或std::string拼dirpath + "/" + entry->d_name,别手写strcat,避免缓冲区溢出 - macOS 上
readdir返回的d_type字段不可靠(常为DT_UNKNOWN),必须调stat实锤类型
跨平台封装时,别把 std::filesystem::path 当字符串拼接
很多人图省事,把 path 对象直接转 .string() 再用 + 拼路径,结果在 Windows 上得到 "C:ooar..ile.txt" 这种含 和 .. 的混乱路径,后续 exists() 可能误判。
正确做法是全程用 std::filesystem::path 的操作符:
- 拼路径用
/(不是+):base / "subdir" / "file.cpp" - 规范化路径用
.lexically_normal(),不是手写正则替换".." - 取文件名用
.filename(),取扩展名用.extension(),别用find_last_of('.') + 1 - 遍历时想跳过隐藏文件(以
.开头),检查entry.path().filename().string()[0] == '.'即可,别用c_str()做指针运算
路径对象内部已处理好不同系统的分隔符差异,强行转字符串再处理,等于放弃标准库最稳的一层抽象。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










