c++遍历目录
#include <iostream>
#include <filesystem>
int main() {
namespace fs = std::filesystem;
// 遍历当前目录
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << '\n';
}
return 0;
}
递归遍历
directory_iterator
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void recursive_directory_traversal(const fs::path& path) {
try {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << '\n';
if (entry.is_directory()) {
recursive_directory_traversal(entry.path());
}
}
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: " << e.what() << '\n';
}
}
int main() {
fs::path start_path = "."; // 开始遍历的目录
recursive_directory_traversal(start_path);
return 0;
}
recursive_directory_iterator
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path start_path = "."; // 当前工作目录
fs::recursive_directory_iterator end_iter;
try {
for (auto it = fs::recursive_directory_iterator(start_path); it != end_iter; ++it) {
if (!it->is_directory()) {
std::cout << it->path() << '\n';
}
}
} catch (const fs::filesystem_error& ex) {
std::cerr << "文件系统错误: " << ex.what() << '\n';
}
return 0;
}
本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0 许可协议。转载请注明来自 张拓的博客!