
在C++中遍历文件夹下的所有文件,尤其是包含子目录的递归遍历,可以通过不同平台的API或跨平台库来实现。下面分别介绍使用Windows API、POSIX(Linux/macOS)以及现代C++17标准中的
<filesystem>
<filesystem>
示例代码:
#include <iostream>void traverse(const fs::path& path) {
for (const auto& entry : fs::recursive_directory_iterator(path)) {
if (entry.is_regular_file()) {
std::cout << "File: " << entry.path().string() << '
';
} else if (entry.is_directory()) {
std::cout << "Dir: " << entry.path().string() << '
';
}
}
}
int main() {
traverse("C:/example"); // 替换为你的路径
return 0;
}
编译时需启用C++17支持,例如g++:
g++ -std=c++17 main.cpp -o main
FindFirstFile
FindNextFile
示例代码:
#include <iostream>void traverse_win32(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;
立即学习“C++免费学习笔记(深入)”;
do {
if (std::string(data.cFileName) == "." || std::string(data.cFileName) == "..")
continue;
std::string fullPath = path + "" + data.cFileName;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::cout << "Dir: " << fullPath << '
';
traverse_win32(fullPath); // 递归进入子目录
} else {
std::cout << "File: " << fullPath << '
';
}
} while (FindNextFileA(hFind, &data));
FindClose(hFind);
}
int main() {
traverse_win32("C:example");
return 0;
}
<dirent.h>
<sys/stat.h>
示例代码:
#include <iostream>bool is_directory(const std::string& path) {
struct stat st;
return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
void traverse_linux(const std::string& path) {
DIR* dir = opendir(path.c_str());
if (!dir) return;
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::string name = entry->d_name;
if (name == "." || name == "..") continue;
std::string fullPath = path + "/" + name;
if (is_directory(fullPath)) {
std::cout << "Dir: " << fullPath << '
';
traverse_linux(fullPath);
} else {
std::cout << "File: " << fullPath << '
';
}
}
closedir(dir);
}
int main() {
traverse_linux("/home/user/example");
return 0;
}
std::filesystem
\
/
/
基本上就这些,选择合适的方法取决于你的目标平台和C++标准支持情况。
以上就是c++++中如何遍历文件夹下的所有文件_C++递归遍历目录文件实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号