C++ 递归遍历 Windows 目录:代码示例与解析
在 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' 替换为你要遍历的目录的路径,然后编译运行代码即可。
原文地址: https://www.cveoy.top/t/topic/qe0b 著作权归作者所有。请勿转载和采集!