使用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;
希望這個方法對和我有一樣困惑的人有所幫助。