
在C++中遍历文件夹下的所有文件,可以使用不同方法,取决于你使用的平台和标准库版本。从C++17开始,std::filesystem 提供了跨平台的便捷方式。如果你使用的是更早的标准或需要兼容老环境,则可借助系统API(如Windows的WIN32_FIND_DATA或POSIX的dirent.h)。
这是目前最简洁、跨平台的方法。你需要包含 filesystem 头文件,并启用C++17支持。
示例代码:
#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;
}
说明:
立即学习“C++免费学习笔记(深入)”;
你可以通过扩展名来筛选文件:
for (const auto & entry : std::filesystem::directory_iterator(path)) {
if (entry.is_regular_file() && entry.path().extension() == ".txt") {
std::cout << "Found text file: " << entry.path().filename() << std::endl;
}
}
使用 std::filesystem::recursive_directory_iterator 可以深入子目录:
for (const auto & entry : std::filesystem::recursive_directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
在没有C++17支持时,Windows下可使用 <windows.h> 中的 FindFirstFile 和 FindNextFile。
#include <iostream>
#include <windows.h>
int main() {
WIN32_FIND_DATA ffd;
HANDLE hFind = FindFirstFile("C:\your_folder\*", &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
std::cout << "Cannot open directory." << std::endl;
return 1;
}
do {
std::cout << ffd.cFileName << std::endl;
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
return 0;
}
在POSIX系统中,可以使用 <dirent.h>:
#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;
}
基本上就这些。现代C++推荐优先使用 std::filesystem,代码清晰且跨平台。编译时注意加上 -std=c++17 和链接选项(如-lstdc++fs 在某些旧g++版本中需要)。
以上就是c++++中怎么遍历文件夹下的所有文件_c++文件夹遍历方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号