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

时间:2015-12-02 20:18:37

标签: c++ windows file directory

我正在用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

1 个答案:

答案 0 :(得分:3)

  

我被告知以下代码应该可以使用

你被告知错了,因为你所呈现的代码严重受损。

  

FindFirstFile操作只找到一个文件(它应该搜索的文件夹的名称)。

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

除此之外,代码还有其他一些问题。

即使枚举正常,您也无法区分文件和子文件夹。

您将错误值传递给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);
}