简体   繁体   中英

How to get a CString object from a file with CFile::Read() in Unicode?

The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards. I write the string into a file with CFile::Write() method:

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

Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?

Thank you very much!

UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);

I would try this, since it can be that the file is larger than what is read (DOS style end line). Read does not set the final \\0, but ReleaseBuffer apparently does, if not called with -1.

UINT nBytes = (UINT)file.GetLength();
UINT nBytesRead = file.Read(strSample.GetBuffer(nBytes+1), nBytes);
strSample.ReleaseBuffer(nBytesRead);

I think you forgot to include the '\\0' at the end

strSample.GetLength() + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM