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++中遍历目录下的所有文件,有多种实现方式,具体取决于操作系统和使用的标准库或第三方库。以下是几种常用且实用的方法。
从 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 上,可以使用 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,但性能良好且控制精细。
在类 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,又需要跨平台,可考虑以下方案:
Boost 示例:
#include <boost/filesystem.hpp> // 用法与 std::filesystem 基本一致
基本上就这些。现代 C++ 推荐使用 <filesystem>,简洁安全,跨平台能力强。旧项目可根据平台选择原生 API 实现。关键是处理好隐藏文件(.开头)和递归需求。
以上就是C++如何遍历一个目录下的所有文件_C++ 目录文件遍历方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号