我用MFC写了一个对话框。
在工程属性里使用Unicode字符集。然后加入一个编辑框空间。在文本编辑框内输入汉字。然后给空间关联了一个CString的变量,然后保存到TXT文件里是乱码。
但是如果在工程属性里使用多字节字符集的话。重复上述步骤,没有乱码出现。。。
求解。。。
为什么使用多字节字符集的话,对话框的按钮都变成Win98那种模式的了?而使用Unicode字符集则有立体感。。
这让我很难抉择啊。。。我是个画面党。。那种按钮确实太难看了。。。
有什么两全的办法吗??
望高人给出解答。。。
谢谢。。。
(注:使用两种字符集都能正常的打开一个TXT文件。。)
打开方式的代码是:
- CFileDialogfileDlg(TRUE);
- fileDlg.m_ofn.lpstrTitle=TEXT("打开文件");
- fileDlg.m_ofn.lpstrFilter=TEXT("文本文件(*.txt)\0*.txt\0\0");
- if(IDOK==fileDlg.DoModal())
- {
- CFilefile(fileDlg.GetPathName(),CFile::modeRead);
- char*ch=newchar[file.GetLength()+1];
- ch[file.GetLength()]=0;
- file.Read(ch,file.GetLength());
- file.Close();
- m_Text=ch;
- }
- UpdateData(FALSE);
m_Text是控件关联的CString变量,直接使用会出错。。。因为找不出什么原因,我new了一个char数组。然后吧char数组的内容给了m_Text。。。。
写入文件的代码是:
- UpdateData();
- CFileDialogfileDlg(FALSE);
- fileDlg.m_ofn.lpstrTitle=TEXT("保存文件");
- fileDlg.m_ofn.lpstrFilter=TEXT("文本文件(*.txt)\0*.txt\0\0");
- fileDlg.m_ofn.lpstrDefExt=TEXT("txt");
- if(IDOK==fileDlg.DoModal())
- {
- CFilefile(fileDlg.GetPathName(),CFile::modeCreate|CFile::modeWrite);
- file.Write(m_Text,m_Text.GetLength());
- file.Close();
- }
写入Unicode文本时,要在文件头部加入Unicode文本标志0XFEFF。
- #include<stdio.h>
- #ifndef_UNICODE
- #define_UNICODE//使用UNICODE编码
- #endif
- #include<Afx.h>//为了使用CString类
- constintUNICODE_TXT_FLG=0xFEFF;//UNICODE文本标示
- intmain()
- {
- FILE*WriteF;
- CStringWstr=_T("一个测试写入文本");
- WriteF=fopen("d:\\test.txt","w+");
- if(WriteF)
- {
- fwrite(&UNICODE_TXT_FLG,2,1,WriteF);//写入头部
- fwrite(Wstr.GetBuffer(10),Wstr.GetLength()*2,1,WriteF);
- fclose(WriteF);
- }
- return0;
- }
MFC代码如下:
- #include<stdio.h>
- #ifndef_UNICODE
- #define_UNICODE
- #endif
- #include<Afx.h>
- constintUNICODE_TXT_FLG=0xFEFF;
- //intmain()
- //{
- //FILE*WriteF;
- //
- //
- //CStringWstr=_T("一个测试写入文本");
- //WriteF=fopen("d:\\test.txt","w+");
- //
- //if(WriteF)
- //{
- //fwrite(&UNICODE_TXT_FLG,2,1,WriteF);
- //fwrite(Wstr.GetBuffer(10),Wstr.GetLength()*2,1,WriteF);
- //fclose(WriteF);
- //}
- //
- //return0;
- //}
- intmain()
- {
- CFileWriteF;
- CStringWstr=_T("一个测试写入文本");
- WriteF.Open(_T("d:\\test.txt"),CFile::modeCreate|CFile::modeWrite);
- if(WriteF)
- {
- WriteF.Write(&UNICODE_TXT_FLG,2);
- WriteF.Write(Wstr.GetBuffer(10),Wstr.GetLength()*2);
- WriteF.Flush();
- WriteF.Close();
- }
- return0;
- }
读的代码如下:
- m_Text.Empty();
- CFileReadF(fileDlg.GetPathName(),CFile::modeRead);
- TCHAR*temp=newTCHAR[ReadF.GetLength()/2+1];
- ReadF.Read(temp,ReadF.GetLength());
- temp[ReadF.GetLength()/2]=0;
- ReadF.Close();
- m_Text=temp;
- deletetemp;
这样的话能正常的写入和打开Unicode字符集的TXT文件了。。
可是那些非Unicode的文件就变成乱码了。。。
是不是应该加个判断语句???应该怎么加??