在 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 函数使用递归的方式深度优先遍历目录。通过 FindFirstFileWFindNextFileW 函数来获取目录下的文件和子目录信息。如果遍历到的是一个子目录,则递归调用 RecursiveTraversal 函数来继续遍历子目录。如果遍历到的是一个文件,则输出文件的路径。

你需要将示例代码中的 folderPath 更改为你要遍历的目录的路径,并根据需要进行修改和扩展。

C++ 深度优先递归遍历目录(Windows 环境)

原文地址: https://www.cveoy.top/t/topic/qe07 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录