C++中遍历文件夹推荐使用C++17的std::filesystem,跨平台且简洁;Windows可用Win32 API如FindFirstFile;Linux/Unix可用dirent.h;旧环境需条件编译适配不同系统。

在C++中遍历文件夹下的所有文件,有多种方式实现,取决于你使用的操作系统和标准库支持程度。下面介绍几种常见且实用的方法。
std::filesystem,它提供了简洁、跨平台的目录遍历接口。示例代码:
#include <iostream>
#include <filesystem>
<p>namespace fs = std::filesystem;</p><p>void traverse_directory(const std::string& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
}</p><p>int main() {
traverse_directory("./test_folder");
return 0;
}
这个方法可以轻松递归遍历子目录:
立即学习“C++免费学习笔记(深入)”;
for (const auto& entry : fs::recursive_directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
编译时需要链接C++17标准:
g++ -std=c++17 your_file.cpp -o your_program
FindFirstFile和FindNextFile函数进行目录遍历。示例代码:
#include <iostream>
#include <windows.h>
<p>void traverse_windows(const std::string& path) {
WIN32_FIND_DATAA ffd;
HANDLE hFind = FindFirstFileA((path + "*").c_str(), &ffd);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (hFind == INVALID_HANDLE_VALUE) {
std::cout << "无法打开目录" << std::endl;
return;
}
do {
if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) {
std::cout << path + "\" + ffd.cFileName << std::endl;
}
} while (FindNextFileA(hFind, &ffd) != 0);
FindClose(hFind);}
这种方式兼容老版本编译器,但仅限Windows平台。
dirent.h头文件来遍历目录。示例代码:
#include <iostream>
#include <dirent.h>
#include <string>
<p>void traverse_linux(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) {
if (std::string(ent->d_name) != "." && std::string(ent->d_name) != "..") {
std::cout << path + "/" + ent->d_name << std::endl;
}
}
closedir(dir);
} else {
std::cout << "无法打开目录" << std::endl;
}}
注意:该方法不支持递归自动进入子目录,需自行判断并递归调用。
filesystem。如果不支持C++17,可封装条件编译逻辑:基本上就这些。现代C++推荐用std::filesystem,简洁安全;旧环境则根据平台选择Win32或dirent方案。只要注意路径分隔符和权限问题,遍历目录并不复杂。
以上就是c++++中怎么遍历文件夹下的所有文件_C++遍历目录文件方法实践的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号