LPCWSTR向量的向量入口已损坏 [英] Corrupted vector entries with LPCWSTR vector

查看:76
本文介绍了LPCWSTR向量的向量入口已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有以下代码.我得到正确填充的向量.但是我无法打印或使用矢量内容,这些矢量内容是目录中的文件名.一旦我输入了第一次迭代.一切都迷路了.我在做什么错了?

I ahve the following piece of code. I get a correctly filled vector. But I am unable to print or use the vector contents which are file names from a directory. As soon as I do enter the first iteration. Everything gets lost. What am I doing wrong?

wprintf - This works OK

wcout-- here is where everything ends up corrupted

#include <windows.h>
#include <sstream>
#include <string>
#include <vector>
#include<iostream>
void GetAllFiles(vector<LPCWSTR>&, wstring);
using namespace std;
void main (void)
{
    vector<LPCWSTR> files(0);
    wstring path = L"Datasets\\Persons\\";
    wstring ext = L"*.*";
    wstring fullPath = path+ext;
    GetAllFiles(files,fullPath);    
    for (unsigned i=0; i<files.size() ; i++)
    {
        try
        {
            wcout<<"::\n"<<files[i];
        }
        catch(exception &ex)
        {
            cout<<"Error:"<<ex.what();
        }
    }

}

void GetAllFiles(vector<LPCWSTR>& fileNames,wstring dir)
{

    WIN32_FIND_DATA search_data;
    memset(&search_data, 0, sizeof(WIN32_FIND_DATA));
    HANDLE handle = FindFirstFile(dir.c_str(),&search_data);
    while(handle != INVALID_HANDLE_VALUE)
    {
        wprintf(L"Found file: %s\r\n", search_data.cFileName);
        fileNames.push_back(search_data.cFileName);
        if(FindNextFile(handle, &search_data) == FALSE)
            break;
    }   
}

我已经附上了输出的屏幕截图.

I have attached a screen shots of the output.

推荐答案

search_data.cFileName是指向由FindFirstFile/FindNextFile迭代器接口控制的内存的指针;您不能存储该指针值,因为指向的内存可能会在每次迭代之间发生变化(甚至在迭代完成后被释放).

search_data.cFileName is a pointer to memory controlled by the FindFirstFile/FindNextFile iterator interface; you cannot store this pointer value as the pointed-to memory could change from iteration to iteration (or even be freed after the iteration completes).

相反,您必须复制字符串以放入向量中,例如使用wcsdup.更好的是,将向量定义为vector<wstring>,以便push_back(search_data.cFileName);创建具有search_data.cFileName内容的wstring.

Instead, you must make a copy of the string to put in your vector, e.g. using wcsdup. Even better, define your vector as a vector<wstring>, so that push_back(search_data.cFileName); creates a wstring with the contents of search_data.cFileName.

这篇关于LPCWSTR向量的向量入口已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆