C++ 获取目录下所有文件绝对路径 (含子文件夹)
可以使用递归函数来实现获取一个目录下所有文件的绝对路径,包括其子文件夹内的文件的绝对路径。
首先,需要使用 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)来表示路径和文件名。
原文地址: https://www.cveoy.top/t/topic/n2zz 著作权归作者所有。请勿转载和采集!