假设ListBox中有以下内容:line1
line2
line3
line4
我现在想将ListBox里的这4行文字写入文本文件中,我是这么做的
void CNewChat::OnOutput() 
{
// TODO: Add your control notification handler code here CString str,fileName("");
CFile file; 

         /*********************这部分不管,这是我用来组建的文件名***************************
fileName.Insert(0,myNick);
fileName.Insert(fileName.GetLength()+1,"-");
fileName.Insert(fileName.GetLength()+1,goalName);
fileName.Insert(fileName.GetLength()+1,".txt");
         /*********************这部分不管,这是我用来组建的文件名*************************** file.Open(fileName,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate);
for (int i=0;i<m_newChatList.GetCount();i++)
{

m_newChatList.GetText( i, str);
file.Write(&str,str.GetLength());

}
file.Close();
}可是问题来了,程序没有错误,文件也能创建,但是我发现里面的内容是乱码,影响到了我后面对文件的读取
我的读取是这么写的
void COpenfileDlg::OnButton1() 
{
m_newChatList.ResetContent(); //创建文件对话框
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | 
OFN_OVERWRITEPROMPT, _T("文本文件(*.*)|*.*||")); if (dlg.DoModal() == IDOK)
{

CString strPathName = dlg.GetPathName(); CStdioFile file;
if (!file.Open(strPathName, CFile::modeRead))
{
::AfxMessageBox(_T("文件打开失败。"));
return;
} //读文件
CString strText = _T("");
while (file.ReadString(strText))
{
m_newChatList.AddString(strText);
}
//关闭文件
file.Close();
}
}这样读出来的也是乱码纠结了。。

解决方案 »

  1.   

    m_newChatList.GetText( i, str);
    str.releasebuffer();
    file.Write(str.getbuffer(),str.GetLength());
      

  2.   

    你的工程编码方式和txt的编码方式不一致。
    使用unicode编程就可以了。
      

  3.   

    file.Write(&str,str.GetLength());
    写进去的是二进制格式,当然打开是乱码建议改为文本格式化读写
      

  4.   

    用file.WriteString()写入txt仍然是亂碼。
    我這邊繁體系統,寫工程遇到好多亂碼問題。只能用unicode編程解決。
      

  5.   

    用CStdioFile ,解决你的问题!
      

  6.   

    // example for CStdioFile::WriteString
    extern CStdioFile f;
    char buf[] = "test string";f.WriteString( buf );