Aurora
Aurora

Reputation: 1364

Strange behaviour with wchar_t* based vector

I'm developing a small function, which iterates through a directory and places the names of all files into a wchar_t* based vector:

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

The problem is that all entries in the vector get overwritten, as soon as a new file name is appended. In other words, all vector entries will contain identical values.

I'm not quite sure why this is happening, since I'm always clearing the buffer before using it for a new entry. Is there a way to remedy this behavior? Any suggestions would be appreciated.

Upvotes: 0

Views: 159

Answers (1)

Zebra North
Zebra North

Reputation: 11492

Your vector is a vector of pointers, and they all point to the same place (szBuf). You need to allocate a new szBuf each time, or better, use a vector of wstring.

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

Upvotes: 4

Related Questions