我正在使用 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/