使用CStdioFile 读取Unicode文件时出现乱码问题解决方案
我们都知道在stdFile.ReadString(temp)中,temp是CString类型,但是我们接收到的数据由于是宽字符
,所以在CEditBox显示有乱码。
可能网上提供了大量的方法将WCHAR或者wchar_t转化为CString的方法,不可少都用到了
MultiByteToWideChar和WideCharToMultiByte方法。
不过我在这里提供一种更为简便的方式,使用CStringA来接收stdFile.ReadString中的数据。
摘自:http://blog.csdn.net/password318/article/details/7003979
使用UNICODE字符集编程时,总是需要使用那些不支持UNICODE的库,例如sqlite3,Lua等必须使用char*
类型的。这个时候用CStringA是最好的。
另外CStringA与CString可以灵活地随意转换赋值,注意不能这样用:
CString str1;
CStringA str2=str1;
而要这样用:
CStringA str2;
str2=str1;
这样就可以把UNICODE版本字符串转换为Ansi版本了,非常之强大,非常之方便!
所以我在这里直接使用CStringA代替CString,获取字符,获取内容正确。
我的代码:
CString temp;
CStringA strTemp;
CString filePath = "logofile.txt"; //加载文件路径(相对路径)
CStdioFile stdFile;
if( stdFile.Open(filePath,CStdioFile::modeRead))
{
while( stdFile.ReadString(temp))
{
strTemp += temp;
strTemp += "\r\n"; //换行
}
stdFile.Close();
}
return strTemp;
希望这个方法对和我有一样困惑的人有所帮助。