我正在开发一个小函数,该函数遍历目录并将所有文件的名称放入基于wchar_t*的向量中:

#include <Windows.h>
#include <tchar.h>
#include <vector>

#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    WIN32_FIND_DATA ffd;

    std::wstring sDir(L"D:\\Test");
    sDir += L"\\*";

    HANDLE hFind = INVALID_HANDLE_VALUE;
    hFind = FindFirstFile(sDir.c_str(), &ffd);

    std::vector<wchar_t*> vctsFiles;
    wchar_t szBuf[MAX_PATH];

    do
    {
        if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            memset(szBuf, 0, sizeof(szBuf));
            ::PathCombine(szBuf, L"D:\\Test", ffd.cFileName);
            vctsFiles.push_back(szBuf);
        }

    } while(FindNextFile(hFind, &ffd) != 0);

    return 0;
}


问题在于,一旦附加了新文件名,向量中的所有条目就会被覆盖。换句话说,所有向量条目将包含相同的值。

我不太确定为什么会这样,因为我总是在将缓冲区用于新条目之前清除缓冲区。有没有办法纠正这种行为?任何建议,将不胜感激。

最佳答案

您的向量是指针的向量,它们都指向同一位置(szBuf)。您每次都需要分配一个new szBuf,或者更好,使用wstring的向量。

std::vector<std::wstring> vctsFiles;

09-25 22:30