
在C++中遍历文件夹下的所有文件和子文件夹,可以使用不同平台的API或跨平台库。下面介绍几种常见实现方式。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void traverse(const fs::path& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "
";
if (entry.is_directory()) {
traverse(entry.path()); // 递归进入子目录
}
}
}
int main() {
fs::path dir = "."; // 当前目录
traverse(dir);
return 0;
}
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <windows.h>
void traverseWindows(const std::string& path) {
std::string searchPath = path + "\*";
WIN32_FIND_DATAA data;
HANDLE hFind = FindFirstFileA(searchPath.c_str(), &data);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
std::string name = data.cFileName;
if (name == "." || name == "..") continue;
std::string fullPath = path + "\" + name;
std::cout << fullPath << "
";
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
traverseWindows(fullPath); // 递归
}
} while (FindNextFileA(hFind, &data));
FindClose(hFind);
}
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
void traverseBoost(const fs::path& path) {
if (!fs::exists(path)) return;
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "
";
if (fs::is_directory(entry.status())) {
traverseBoost(entry.path());
}
}
}
以上就是c++++怎么遍历一个文件夹下的所有文件_文件夹遍历实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号