
在C++中遍历文件夹下的所有文件,尤其是包含子目录的递归遍历,可以通过不同平台的API或跨平台库来实现。下面分别介绍使用Windows API、POSIX(Linux/macOS)以及现代C++17标准中的
方法。
使用C++17 filesystem(推荐)
C++17引入了头文件,提供了跨平台的文件系统操作支持,是目前最简洁、安全的方式。
示例代码:
#include iostream>#include
namespace fs = std::filesystem;
void traverse(const fs::path& path) {
for (const auto& entry : fs::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout
} else if (entry.is_directory()) {
std::cout
}
}
}
int main() {
traverse("C:/example"); // 替换为你的路径
return 0;
}
编译时需启用C++17支持,例如g++:
g++ -std=c++17 main.cpp -o main
Windows平台:使用Win32 API
在Windows下可使用FindFirstFile和
FindNextFile进行递归遍历。
示例代码:
#include#include windows.h>
#include
void traverse_win32(const std::string& path) {
std::string searchPath = path + "\*";
WIN32_FIND_DATAA data;
HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);
if (hFind == INVALID_HANDLE_VALUE) return;
立即学习“C++免费学习笔记(深入)”;
do {
if (std::string(data.cFileName) == "." || std::string(data.cFileName) == "..")
continue;
std::string fullPath = path + "\" + data.cFileName;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::cout
traverse_win32(fullPath); // 递归进入子目录
} else {
std::cout
}
} while (FindNextFileA(hFind, &data));
FindClose(hFind);
}
int main() {
traverse_win32("C:\example");
return 0;
}
Linux/Unix:使用dirent.h
在POSIX系统中,可以使用和
进行递归遍历。
示例代码:
#include#include
#include
#include
#include
bool is_directory(const std::string& path) {
struct stat st;
return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
void traverse_linux(const std::string& path) {
DIR* dir = opendir(path.c_str());
if (!dir) return;
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::string name = entry->d_name;
if (name == "." || name == "..") continue;
std::string fullPath = path + "/" + name;
if (is_directory(fullPath)) {
std::cout
traverse_linux(fullPath);
} else {
std::cout
}
}
closedir(dir);
}
int main() {
traverse_linux("/home/user/example");
return 0;
}
注意事项与建议
- 推荐优先使用C++17的std::filesystem,代码简洁且跨平台。
- 注意路径分隔符:Windows用反斜杠
\\,Linux用
/,可用条件编译或统一使用
/(多数系统支持)。
- 递归深度过大可能导致栈溢出,可改用栈结构模拟递归。
- 处理中文路径时确保编码一致,Windows建议使用宽字符版本API(如FindFirstFileW)。
基本上就这些,选择合适的方法取决于你的目标平台和C++标准支持情况。










