
在C++中遍历一个文件夹下的所有文件,有多种实现方式,取决于你使用的平台和标准库。下面介绍几种常用的方法,包括跨平台和特定平台的实现。
需要包含头文件 <filesystem>,并启用 C++17 支持。
示例代码:
#include <iostream>
#include <filesystem>
<p>namespace fs = std::filesystem;</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><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 : fs::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
} catch (const fs::filesystem_error& ex) {
std::cerr << "Error accessing directory: " << ex.what() << std::endl;
}
return 0;}
如果只想遍历文件(排除子目录),可以加判断:
for (const auto& entry : fs::directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "File: " << entry.path().filename() << std::endl;
}
}
递归遍历子目录使用 fs::recursive_directory_iterator:
for (const auto& entry : fs::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "Found file: " << entry.path() << std::endl;
}
}
#include <iostream>
#include <windows.h>
<p>int main() {
WIN32_FIND_DATA data;
HANDLE hFind = FindFirstFile(".\<em>.</em>", &data); // 当前目录下所有文件</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (hFind == INVALID_HANDLE_VALUE) {
std::cerr << "Cannot open directory." << std::endl;
return 1;
}
do {
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::cout << "[DIR] " << data.cFileName << std::endl;
} else {
std::cout << "[FILE] " << data.cFileName << std::endl;
}
} while (FindNextFile(hFind, &data));
FindClose(hFind);
return 0;}
注意:这种方式不递归,仅列出当前目录内容。
#include <iostream>
#include <dirent.h>
#include <string>
<p>int main() {
DIR<em> dir;
struct dirent</em> ent;
std::string path = "./";</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 (ent->d_type == DT_REG) {
std::cout << "[FILE] " << ent->d_name << std::endl;
} else if (ent->d_type == DT_DIR) {
std::cout << "[DIR] " << ent->d_name << std::endl;
}
}
closedir(dir);
} else {
std::cerr << "Could not open directory." << std::endl;
return 1;
}
return 0;}
如果不支持 C++17,可考虑:
基本上就这些方法。现代 C++ 优先选 filesystem,老项目再考虑平台 API。编译时记得开启 -std=c++17,并链接 stdc++fs(某些旧编译器需要)。
以上就是c++++怎么遍历一个文件夹下的所有文件_c++遍历目录文件实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号