可以使用递归函数来实现获取一个目录下所有文件的绝对路径,包括其子文件夹内的文件的绝对路径。

首先,需要使用Windows API中的FindFirstFile和FindNextFile函数来遍历目录下的文件和子文件夹。

然后,在遍历到文件时,可以使用GetFullPathName函数来获取文件的绝对路径。

在遍历到子文件夹时,可以使用递归函数来获取子文件夹内的文件的绝对路径。

下面是一个示例代码:

#include <iostream>
#include <windows.h>

void TraverseDirectory(const std::wstring& path)
{
    WIN32_FIND_DATAW data;
    HANDLE hFind = FindFirstFileW((path + L"\\*").c_str(), &data);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if (wcscmp(data.cFileName, L".") == 0 || wcscmp(data.cFileName, L"..") == 0)
            {
                continue;
            }

            if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                std::wstring subPath = path + L"\\" + data.cFileName;
                TraverseDirectory(subPath);
            }
            else
            {
                std::wstring filePath = path + L"\\" + data.cFileName;
                std::wcout << filePath << std::endl;
            }
        } while (FindNextFileW(hFind, &data));
        FindClose(hFind);
    }
}

int main()
{
    std::wstring path = L"C:\\Windows";
    TraverseDirectory(path);
    return 0;
}

在示例代码中,TraverseDirectory函数接收一个目录路径作为参数,遍历该目录下的文件和子文件夹,并输出每个文件的绝对路径。

在遍历到子文件夹时,递归调用TraverseDirectory函数来获取子文件夹内的文件的绝对路径。

注意,在使用Windows API函数时,需要使用宽字符类型(如std::wstring)来表示路径和文件名

c++获取一个目录下所有文件的绝对路径包括其子文件夹内的文件的绝对路径

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

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