
在C++中遍历文件夹下的所有文件,有多种方法,取决于你使用的平台和标准库版本。以下是几种常用且实用的方式。
std::filesystem,可以跨平台地遍历目录,非常方便。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <filesystem>
int main() {
std::string path = "your_folder_path"; // 替换为你的文件夹路径
for (const auto &entry : std::filesystem::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
return 0;
}
if (entry.is_regular_file()) {
std::cout << "File: " << entry.path().filename() << std::endl;
}
g++ -std=c++17 your_code.cpp -lstdc++fs
FindFirstFile和FindNextFile来遍历文件夹。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <windows.h>
int main() {
WIN32_FIND_DATAA data;
HANDLE hFind = FindFirstFileA("C:\your\folder\*", &data);
if (hFind == INVALID_HANDLE_VALUE) {
std::cout << "Cannot open directory." << std::endl;
return 1;
}
do {
std::cout << data.cFileName << std::endl;
} while (FindNextFileA(hFind, &data));
FindClose(hFind);
return 0;
}
if (strcmp(data.cFileName, ".") == 0 || strcmp(data.cFileName, "..") == 0)
continue;
<dirent.h>提供的接口进行目录操作。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
if ((dir = opendir("your_folder_path")) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
std::cout << ent->d_name << std::endl;
}
closedir(dir);
} else {
std::cerr << "Could not open directory" << std::endl;
return 1;
}
return 0;
}
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
std::filesystem最简单:
for (const auto &entry : std::filesystem::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "File: " << entry.path() << std::endl;
}
}
基本上就这些。现代C++优先使用std::filesystem,简洁安全。旧项目或特定平台可选原生API。关键是根据编译环境选择合适方法。不复杂但容易忽略细节,比如权限、路径格式和隐藏项处理。
以上就是c++++如何遍历文件夹下的所有文件_c++文件夹遍历方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号