程序是Unicode Debug版, 需要将一段含有中文的字串保存到一个TXT文件中去,代码如下:CFile file(TEXT("C:\\Msg.txt"), CFile::modeCreate|CFile::modeWrite);CString str(TEXT("I love 中华人民共和国, I love!"));TCHAR *pBuff = str.GetBuffer(str.GetLength());
str.ReleaseBuffer();

file.Write(pBuff, str.GetLength());file.Close();运行得到的结果是Msg.txt中的两个I love都能正常写入, 唯有“中华人民共和国”这一段中文是乱码! 这是为何?另: 如果str.GetLength()不乘2这只能保存str的前半段, 这又是为何?菜鸟问题,请多指教!

解决方案 »

  1.   

    CFile   cf;
    cf.Open(_T("e:\\test.txt"),CFile::modeCreate | CFile::modeReadWrite);

    CString   str;
    str = _T("I love 中华人民共和国 very"); cf.Write(str,str.GetLength());
    cf.Close();
      

  2.   

    是吗?
    怎么在我这里就有问题了?
    你们的Link和C++里的设置都是写什么?
      

  3.   

    我的Project Setting中的预定义设置如下:WIN32,_DEBUG,_WINDOWS,_AFXDLL,_MBCS,_UNICODE,UNICODE,DEBUG与你们的有什么不同吗?
      

  4.   

    如果str.GetLength()不乘2这只能保存str的前半段, 这又是为何?
    一个汉字是两个字节,这个应该知道吧!
      

  5.   

    file.Write(pBuff,str.GetLength() * 2);
      

  6.   

    CFile file(TEXT("C:\\Msg.txt"), CFile::modeCreate|CFile::modeWrite);
    CArchive tempArchive( &file, CArchive::store ) ;CString str(TEXT("I love 中華人民共和国, I love!"));// 写入Unicode头
    UINT WriteBuffer = 0xFEFF ;
    tempArchive.Write( &WriteBuffer, sizeof( _TCHAR ) ) ;
    tempArchive.WriteString(str);//TCHAR *pBuff = str.GetBuffer(str.GetLength());
    //str.ReleaseBuffer();
    tempArchive.Close();
    //file.Write(pBuff, str.GetLength());file.Close();
      

  7.   

    我的代码在DEBUG下可得到正确结果,但在UNICODE DEBUG下得不到正确结果。先试试semiconduct的方法。
      

  8.   

    semicoduct的方法可行。
    但是如何在写入的两个CString之间换行呢?菜鸟问题, 不好意思。
      

  9.   

    CFile file(TEXT("C:\\Msg.txt"), CFile::modeCreate|CFile::modeWrite);
    CArchive tempArchive( &file, CArchive::store ) ;
    TCHAR tempChars[1024] = _T("");// 写入Unicode头
    UINT WriteBuffer = 0xFEFF ;
    tempArchive.Write( &WriteBuffer, sizeof( _TCHAR ) ) ;
    //tempArchive.WriteString(str);_tcscat( tempChars, _T("中华人民共和国") );
    _tcscat( tempChars, _T("\r\n"));
    _tcscat( tempChars, _T("中国软件") );tempArchive.Write( tempChars, _tcslen(tempChars)*sizeof( _TCHAR ) );tempArchive.Close();
    file.Close();不知道理解错误你的问题没有。