
在C++中遍历文件夹中的所有文件,有多种方式,取决于你使用的平台和标准库版本。下面介绍几种常见且实用的方法。
从 C++17 开始,std::filesystem 成为标准库的一部分,提供了跨平台的文件系统操作支持,遍历文件夹变得非常简单。
示例代码:
#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>void traverse_directory(const std::string& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "
";
}
}</p><p>int main() {
traverse_directory("C:/your/folder/path");
return 0;
}</p>说明:
entry.is_regular_file()、entry.is_directory()。要使用 std::filesystem,注意以下几点:
在不支持 C++17 的旧项目中,Windows 下可以使用 FindFirstFile 和 FindNextFile。
#include <iostream>
#include <windows.h>
<p>void traverse_win32(const std::string& path) {
WIN32_FIND_DATAA data;
std::string searchPath = path + "*";</p><pre class='brush:php;toolbar:false;'>HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
std::cout << (path + "\" + data.cFileName) << "
";
} while (FindNextFileA(hFind, &data));
FindClose(hFind);}
说明:
data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY。在类 Unix 系统中,可使用 <dirent.h> 提供的函数。
#include <iostream>
#include <dirent.h>
<p>void traverse_unix(const std::string& path) {
DIR<em> dir;
struct dirent</em> ent;</p><pre class='brush:php;toolbar:false;'>if ((dir = opendir(path.c_str())) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
std::cout << path + "/" + ent->d_name << "
";
}
closedir(dir);
}}
说明:
基本上就这些。现代 C++ 推荐优先使用 std::filesystem,简洁、安全、跨平台。旧项目可根据平台选择 Win32 或 POSIX 方法。关键在于根据编译环境和目标平台合理选型。
以上就是c++++怎么遍历文件夹中的所有文件_c++文件夹遍历方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号