使用C++17的std::filesystem可跨平台遍历文件夹,支持常规和递归遍历,Windows可用Win32 API,Linux可用dirent.h,推荐优先使用std::filesystem。

在C++中遍历一个文件夹下的所有文件,可以使用不同操作系统提供的API,也可以借助标准库或第三方库来实现跨平台操作。以下是几种常见的实现方式。
std::filesystem库,提供了便捷的目录遍历功能,跨平台且易于使用。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <filesystem>
<p>int main() {
std::string path = "./test_folder"; // 替换为你要遍历的路径</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">try {
for (const auto& entry : std::filesystem::directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "文件: " << entry.path().filename() << '\n';
} else if (entry.is_directory()) {
std::cout << "目录: " << entry.path().filename() << '\n';
}
}
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << '\n';
}
return 0;} 编译时需要启用C++17支持:
g++ -std=c++17 your_file.cpp -o your_program
std::filesystem::recursive_directory_iterator。示例:
for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "发现文件: " << entry.path().string() << '\n';
}
}
FindFirstFile和FindNextFile函数遍历目录。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <windows.h>
<p>void listFilesWin32(const std::string& path) {
WIN32_FIND_DATAA data;
std::string searchPath = path + "\*";
HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (hFind == INVALID_HANDLE_VALUE) {
std::cerr << "无法打开目录\n";
return;
}
do {
std::string name = data.cFileName;
if (name == "." || name == "..") continue;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::cout << "目录: " << name << '\n';
} else {
std::cout << "文件: " << name << '\n';
}
} while (FindNextFileA(hFind, &data));
FindClose(hFind);}
<dirent.h>头文件中的函数进行目录操作。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <dirent.h>
#include <string>
<p>void listFilesLinux(const std::string& path) {
DIR<em> dir;
struct dirent</em> ent;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if ((dir = opendir(path.c_str())) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
std::string name = ent->d_name;
if (name == "." || name == "..") continue;
if (ent->d_type == DT_DIR) {
std::cout << "目录: " << name << '\n';
} else {
std::cout << "文件: " << name << '\n';
}
}
closedir(dir);
} else {
std::cerr << "无法打开目录\n";
}}
总结建议:
std::filesystem,简洁、安全、跨平台。dirent.h。基本上就这些方法,按需选择即可。
以上就是c++++中怎么遍历一个文件夹下的所有文件_遍历目录文件实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号