windows环境使用c++递归遍历一个目录
要在Windows环境下使用C++递归遍历一个目录,可以使用Windows API来实现。下面是一个示例代码,演示了如何递归遍历目录并打印出所有文件和子目录的路径。
#include <windows.h>
#include <iostream>
#include <string>
void RecursiveDirectoryTraversal(const std::string& path) {
std::string searchPath = path + "\\*";
WIN32_FIND_DATA findData;
HANDLE hFind = FindFirstFile(searchPath.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE) {
std::cout << "Failed to find first file!" << std::endl;
return;
}
do {
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// 忽略当前目录和父级目录
if (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0) {
std::string newPath = path + "\\" + findData.cFileName;
std::cout << "Directory: " << newPath << std::endl;
RecursiveDirectoryTraversal(newPath);
}
}
else {
std::string filePath = path + "\\" + findData.cFileName;
std::cout << "File: " << filePath << std::endl;
}
} while (FindNextFile(hFind, &findData));
FindClose(hFind);
}
int main() {
std::string directoryPath = "C:\\path\\to\\directory";
RecursiveDirectoryTraversal(directoryPath);
return 0;
}
在上面的代码中,RecursiveDirectoryTraversal函数使用FindFirstFile和FindNextFile函数来遍历指定目录下的文件和子目录。如果找到的是子目录,则递归调用RecursiveDirectoryTraversal函数来继续遍历子目录。如果找到的是文件,则直接打印出文件的路径。
你只需要将代码中的"C:\\path\\to\\directory"替换为你要遍历的目录的路径,然后编译运行代码即可
原文地址: http://www.cveoy.top/t/topic/ixIO 著作权归作者所有。请勿转载和采集!