C ++函数神秘破坏vector <lpcwstr>

时间:2019-03-30 18:53:47

标签: c++ winapi

我调用一个函数来获取目录中的所有文件,并将它们的路径放在向量LPCWSTR中,当代码从该函数返回时,向量LPCWSTR被该函数之后执行的所有操作(甚至消息框)所破坏。这是一个简单的非多线程应用程序。

我尝试将“ out.push_back(fileNameCombined)”更改为硬编码路径,即out.push_back(L“ C:/Users/username/Desktop/New/XoaxLogo.bmp”);完成此操作后,矢量LPCWSTR对象不会损坏。不确定这能告诉我什么。

void GetFilesInDirectory(std::vector<LPCWSTR> &out, const LPCWSTR &directory)
{
HANDLE dir;
WIN32_FIND_DATAW file_data;

WCHAR dirCombined[MAX_PATH];
WCHAR fileNameCombined[MAX_PATH];

if (PathCombine(dirCombined, directory, L"/*") == NULL) {
    return;
}

if ((dir = FindFirstFileW(dirCombined, &file_data)) == INVALID_HANDLE_VALUE)
    return; /* No files found */

do {
    const LPCWSTR file_name = file_data.cFileName;

    if (PathCombineW(dirCombined, directory, L"/") == NULL) {
        return;
    }

    if (PathCombineW(fileNameCombined, dirCombined, file_name) == NULL) {
        return;
    }

    const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

    if (file_name[0] == '.')
        continue;

    if (is_directory)
        continue;

    out.push_back(fileNameCombined);
} while (FindNextFile(dir, &file_data));

FindClose(dir);
MessageBoxW(nullptr, out[0], L"test", 0); // File name is ok at this point.
} 

这是调用代码:

std::vector<LPCWSTR> imageList;
GetFilesInDirectory(imageList, L"C:/users/username/desktop/new");
MessageBoxW(nullptr, imageList[0], L"test", 0); 
// file name is mangled at this point, the first byte is null and the rest is garbage.

0 个答案:

没有答案