c++ - 无法使用 CMemFile::Detach() 复制 CMemFile 中存在的数据

标签 c++ mfc visual-c++

我正在使用 CMemFile::Write() 在内存中写入两行:

void CLISTCTRLDlg::Export(LPTSTR *pBlock)
{
 CMemFile outMem(32768);

 CString csHeader = _T("EmpId EmpName EmpAddress\n");
 outMem.Write(csHeader.GetBuffer(0), csHeader.GetLength());

 CString csInfo = _T("1 TestName TestAddress\n");
 outMem.Write(csInfo.GetBuffer(0), csInfo.GetLength());

 long lLen = outMem.GetLength() + 1;
 BYTE *mBlock = outMem.Detach();
 *pBlock = (LPTSTR) malloc(sizeof(char) * lLen);
 memcpy(*pBlock, mBlock, lLen-1);
 (*pBlock)[lLen -1] = 0;
 OutputDebugStringW(*pBlock);
 free(outMem);
}

输出窗口显示字符串“EmpId EmpNam? ?????????? ??????????”当 OutputDebugStringW(*pBlock); 语句被执行时。

我不明白为什么数据会被截断。

此外,当语句free(outMem);被执行时,系统会抛出一个未处理的异常。

谁能指导我找到解决方案并让我知道我错在哪里?

谢谢。

最佳答案

无需将事情复杂化,即可存储:

CMemFile file;
CArchive archive(&file, CArchive::store);

CString csHeader = _T("EmpId EmpName EmpAddress\n");
archive << csHeader;

CString csInfo = _T("1 TestName TestAddress\n");
archve << csInfo;

archive.Close();

加载:

file.Seek(0, 0); // rewind the file
CArchive archive(&file, CArchive::load);

CString temp;
archive >> temp;

无需使用 memcpy 或摆弄内存。

关于c++ - 无法使用 CMemFile::Detach() 复制 CMemFile 中存在的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2153386/

相关文章:

c++ - basic_regex 使用 char32_t 抛出 bad_cast

C++ 动态数组大小定义

windows - 如何在 MFC 中获取 CString 宽度(对于 Unicode)?

c++ - 如何通过 C++ 使用 Google Translate API

c++ - 找不到头文件 iostream Visual Studio 2010

c++ - 有效地杀死一个windows进程

android - 我们可以在 android 上使用 flex 和 c++ 吗?

c++ - 虚拟列表控件 (MFC)

c++ - 如何在 _T 包装器中使用变量?

c++ - 将 _beginthread 返回的 uintptr_t 转换为 HANDLE 是否安全?