簡體   English   中英

如何獲取目錄中的所有文件名?

[英]How can I obtain all of the file names in a 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

我被告知以下代碼應該有效

您被告知錯了,因為您提供的代碼嚴重破壞。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM