windows环境使用c++深度优先递归遍历一个目录
在Windows环境下使用C++,可以使用Windows API来实现深度优先递归遍历一个目录。下面是一个示例代码:
#include <iostream>
#include <windows.h>
#include <string>
void RecursiveTraversal(const std::wstring& folderPath)
{
WIN32_FIND_DATAW findData;
std::wstring searchPath = folderPath + L"\\*";
HANDLE hFind = FindFirstFileW(searchPath.c_str(), &findData);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
if (wcscmp(findData.cFileName, L".") == 0 || wcscmp(findData.cFileName, L"..") == 0)
{
continue;
}
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // 目录
{
std::wstring subFolderPath = folderPath + L"\\" + findData.cFileName;
RecursiveTraversal(subFolderPath);
}
else // 文件
{
std::wstring filePath = folderPath + L"\\" + findData.cFileName;
std::wcout << filePath << std::endl;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
}
int main()
{
std::wstring folderPath = L"C:\\Path\\To\\Directory";
RecursiveTraversal(folderPath);
return 0;
}
在上述示例代码中,RecursiveTraversal函数使用递归的方式深度优先遍历目录。通过FindFirstFileW和FindNextFileW函数来获取目录下的文件和子目录信息。如果遍历到的是一个子目录,则递归调用RecursiveTraversal函数来继续遍历子目录。如果遍历到的是一个文件,则输出文件的路径。
你需要将示例代码中的folderPath更改为你要遍历的目录的路径,并根据需要进行修改和扩展
原文地址: https://www.cveoy.top/t/topic/ixJZ 著作权归作者所有。请勿转载和采集!