【问题标题】:How to get a CString object from a file with CFile::Read() in Unicode?如何从 Unicode 中的 CFile::Read() 文件中获取 CString 对象?
【发布时间】:2009-09-27 07:57:48
【问题描述】:

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

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

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

非常感谢!

【问题讨论】:

  • 请注意,对 GetBuffer 的调用是多余的,并且可能会导致问题,因为它有一些副作用。在这里,您只需要一个 LPCTSTR,所以只需使用 (LPCTSTR)strSample 左右。它安全且效率更高(只是不要那样修改字符串)。如果确实调用了 GetBuffer,请确保之后调用 ReleaseBuffer。
  • 我使用 (LPCTSTR)strSample 将字符串写入文件时可以。但是如何使用 (LPCTSTR)strsample 从文件中读取字符串?

标签: c++ unicode cstring cfile


【解决方案1】:
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);

【讨论】:

    【解决方案2】:

    我想你忘了在末尾加上“\0”

    strSample.GetLength() + 1

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多