2

字符集是 Unicode。我想将一个 CString 类型的字符串写入一个文件,然后再从文件中读出它。我使用 CFile::Write() 方法将字符串写入文件:

int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);

这是一个问题:我想从包含 strSample 内容的文件中获取 CString。我该怎么做?

非常感谢!

4

3 回答 3

5
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
于 2009-09-27T13:26:44.120 回答
0

我会试试这个,因为文件可能比读取的文件大(DOS 风格的结束行)。Read 不会设置最终的 \0,但如果没有使用 -1 调用,ReleaseBuffer 显然会这样做。

UINT nBytes = (UINT)file.GetLength();
UINT nBytesRead = file.Read(strSample.GetBuffer(nBytes+1), nBytes);
strSample.ReleaseBuffer(nBytesRead);
于 2015-02-12T12:48:23.140 回答
0

我想你忘了在最后加上 '\0'

strSample.GetLength() + 1

于 2011-06-24T03:23:23.477 回答