
在C++中遍历文件夹下的所有文件,可以使用不同方法,取决于你使用的平台和标准库版本。从C++17开始,std::filesystem 提供了跨平台的便捷方式。如果你使用的是更早的标准或需要兼容老环境,则可借助系统API(如Windows的WIN32_FIND_DATA或POSIX的dirent.h)。
使用C++17 std::filesystem(推荐)
这是目前最简洁、跨平台的方法。你需要包含 filesystem 头文件,并启用C++17支持。
示例代码:
#include#include int main() { std::string path = "your_folder_path"; // 替换为你的路径 for (const auto & entry : std::filesystem::directory_iterator(path)) { std::cout << entry.path() << std::endl; } return 0; }
说明:
立即学习“C++免费学习笔记(深入)”;
- std::filesystem::directory_iterator 遍历指定目录下的所有条目(包括文件和子目录)。
- entry.path() 返回完整路径。
- 若只想要普通文件,可用 entry.is_regular_file() 判断。
过滤特定类型文件
你可以通过扩展名来筛选文件:
for (const auto & entry : std::filesystem::directory_iterator(path)) {
if (entry.is_regular_file() && entry.path().extension() == ".txt") {
std::cout << "Found text file: " << entry.path().filename() << std::endl;
}
}
递归遍历子目录
使用 std::filesystem::recursive_directory_iterator 可以深入子目录:
for (const auto & entry : std::filesystem::recursive_directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
兼容旧版本:Windows API(仅Windows)
在没有C++17支持时,Windows下可使用 windows.h> 中的 FindFirstFile 和 FindNextFile。
#include#include int main() { WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile("C:\\your_folder\\*", &ffd); if (hFind == INVALID_HANDLE_VALUE) { std::cout << "Cannot open directory." << std::endl; return 1; } do { std::cout << ffd.cFileName << std::endl; } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); return 0; }
Linux/Unix:使用 dirent.h
在POSIX系统中,可以使用
#include#include int main() { DIR *dir; struct dirent *ent; if ((dir = opendir("your_folder_path")) != nullptr) { while ((ent = readdir(dir)) != nullptr) { std::cout << ent->d_name << std::endl; } closedir(dir); } else { std::cerr << "Could not open directory" << std::endl; return 1; } return 0; }
基本上就这些。现代C++推荐优先使用 std::filesystem,代码清晰且跨平台。编译时注意加上 -std=c++17 和链接选项(如-lstdc++fs 在某些旧g++版本中需要)。











