2

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!

IAdapter
  • 62,595
  • 73
  • 179
  • 242
quantity
  • 4,051
  • 3
  • 23
  • 20
  • 2
    Note that the call to GetBuffer is redundant, and might cause problems as it has some side effects. Here, all you need is a LPCTSTR, so just use (LPCTSTR)strSample or so. It safe, and much more efficient (just don't modify the string that way). If you do call GetBuffer, make sure you call ReleaseBuffer afterwards. – Eran Sep 27 '09 at 19:45
  • It's OK when I use (LPCTSTR)strSample to write a string into file. But how do I read the string from the file with (LPCTSTR)strsample? – quantity Sep 28 '09 at 03:45

3 Answers3

5
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
Luke
  • 11,211
  • 2
  • 27
  • 38
0

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);
R Risack
  • 69
  • 8
0

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

strSample.GetLength() + 1

likejudo
  • 3,396
  • 6
  • 52
  • 107