如何获取目录中的所有文件名

How can I obtain all of the file names in a directory?

本文关键字:文件名 何获取 获取      更新时间:2023-10-16

我正在用C++编写一个程序。我正在尝试获取程序可执行文件所在的文件夹中的所有文件,并将它们存储在矢量中。有人告诉我,以下代码应该可以工作,但 FindFirstFile 操作只找到一个文件(它应该搜索的文件夹的名称(。如何更改代码以使其正确查看文件夹?

std::vector<char*> fileArray;
//Get location of program executable
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
//Remove the executable file name from 'path' so that it refers to the folder instead
PathCchRemoveFileSpec(path, sizeof(path));
//This code should find the first file in the executable folder, but it fails
//Instead, it obtains the name of the folder that it is searching
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFile(path, &ffd);
do
{
    //The name of the folder is pushed onto the array because of the previous code's mistake
    //e.g. If the folder is "C:\MyFolder", it stores "MyFolder"
    fileArray.push_back(ffd.cFileName); //Disclaimer: This line of code won't add the file name properly (I'll get to fixing it later), but that's not relevant to the question
} while (FindNextFile(hFind, &ffd) != 0); //This line fails to find anymore files

有人告诉我以下代码应该可以工作

你被告知错了,因为你提供的代码被严重破坏了。

FindFirstFile 操作仅查找一个文件(应搜索的文件夹的名称(。

您只是将文件夹路径本身传递给FindFirstFile(),因此只会报告一个条目,描述文件夹本身。 您需要做的是在路径末尾附加一个**.*通配符,然后FindFirstFile()/FindNextFile()将枚举文件夹中的文件和子文件夹。

除此之外,代码还有其他几个问题。

即使枚举有效,也不会区分文件和子文件夹。

您正在将错误的值传递给 PathCchRemoveFileSpec() 的第二个参数。 您正在传入字节计数,但它需要字符计数。

您没有在进入循环之前检查FindFirstFile()是否失败,也没有在循环完成后调用FindClose()

最后,您的代码甚至不会按原样编译。 您的vector存储char*值,但是为了将WCHAR[]传递给FindFirstFile(),必须定义UNICODE,这意味着FindFirstFile()将映射到FindFirstFileW()WIN32_FIND_DATA将映射到WIN32_FIND_DATAW,因此cFileName字段将是一个WCHAR[]。 编译器不允许将WCHAR[](或WCHAR*)分配给char*

尝试更多类似的东西:

std::vector<std::wstring> fileArray;
//Get location of program executable
WCHAR path[MAX_PATH+1] = {0};
GetModuleFileNameW(NULL, path, MAX_PATH);
//Remove the executable file name from 'path' so that it refers to the folder instead
PathCchRemoveFileSpec(path, MAX_PATH);
// append a wildcard to the path
PathCchAppend(path, MAX_PATH, L"*.*");
WIN32_FIND_DATAW ffd;
HANDLE hFind = FindFirstFileW(path, &ffd);
if (hFile != INVALID_HANDLE_VALUE)
{
    do
    {
        if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
            fileArray.push_back(ffd.cFileName);
    }
    while (FindNextFileW(hFind, &ffd));
    FindClose(hFind);
}