在C++中遍历文件夹下的所有文件,尤其是包含子目录的递归遍历,可以通过不同平台的API或跨平台库来实现。下面分别介绍使用Windows API、POSIX(Linux/macOS)以及现代C++17标准中的
<filesystem>
方法。
使用C++17 filesystem(推荐)
C++17引入了
<filesystem>
头文件,提供了跨平台的文件系统操作支持,是目前最简洁、安全的方式。
示例代码:
#include <iostream>
#include <filesystem>
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 << “File: ” << entry.path().string() << ‘ ‘;
} else if (entry.is_directory()) {
std::cout << “Dir: ” << entry.path().string() << ‘ ‘;
}
}
}
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 <iostream>
#include <windows.h>
#include <string>
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 << “Dir: ” << fullPath << ‘ ‘;
traverse_win32(fullPath); // 递归进入子目录
} else {
std::cout << “File: ” << fullPath << ‘ ‘;
}
} while (FindNextFileA(hFind, &data));
FindClose(hFind);
}
int main() {
traverse_win32(“C:example”);
return 0;
}
Linux/Unix:使用dirent.h
在POSIX系统中,可以使用
<dirent.h>
和
<sys/stat.h>
进行递归遍历。
示例代码:
#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>
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 << “Dir: ” << fullPath << ‘ ‘;
traverse_linux(fullPath);
} else {
std::cout << “File: ” << fullPath << ‘ ‘;
}
}
closedir(dir);
}
int main() {
traverse_linux(“/home/user/example”);
return 0;
}
注意事项与建议
– 推荐优先使用C++17的
std::filesystem
,代码简洁且跨平台。
– 注意路径分隔符:Windows用反斜杠
,Linux用
/
,可用条件编译或统一使用
/
(多数系统支持)。
– 递归深度过大可能导致栈溢出,可改用栈结构模拟递归。
– 处理中文路径时确保编码一致,Windows建议使用宽字符版本API(如FindFirstFileW)。
基本上就这些,选择合适的方法取决于你的目标平台和C++标准支持情况。
linux windows 编码 mac 栈 ai unix c++ ios macos win cos String if for while include Filesystem const auto continue 递归 bool int void 栈 Struct Namespace windows macos linux unix