txt文本是unicode编码格式,但ReadString后,显示汉字是乱码的。以下是解决办法。
CString CSetupForm::GetTxtfile(CString txtdir) //参数为文件路径
{CStdioFile file;
if(file.Open(txtdir,CFile::modeNoTruncate | CFile::modeRead | CFile::typeText))
{
CString str;
CString textcontent=_T("");
while(file.ReadString(str))
{
if(ReadStringToUnicode(str)) //这里要处理下,不然汉字无法正常显示。函数见下面
textcontent=textcontent+_T("\r\n")+str;
}
file.Close();
return textcontent;
}
else
{
return _T("");
}
}
//这个函数我是引用别人的,但是原版有问题。总是会显示一个“铪“字出来。检查了下,发现问题在于没有字符的结束符。
BOOL ReadStringToUnicode(CString &str)
{
char *szBuf = new char[ str.GetLength()+1]; //数量要加1
for (int i = 0 ; i < str.GetLength(); i++)
{
szBuf[i] = (CHAR)str.GetAt(i);
}
szBuf[str.GetLength()]='\0'; //这里,必须要加上,否则会在结尾片显示一个"铪"字。
// USES_CONVERSION;
//char * sz=W2A(str.GetBuffer()); //这些方法我都试过,不行的。
BOOL bok= CharToUnicode(szBuf , &str);
delete []szBuf;
return bok;
}
//此函数是原版引用的。不需要任何更改
/
// 将Char型字符转换为Unicode字符
int CharToUnicode(char *pchIn, CString *pstrOut)
{
int nLen;
WCHAR *ptch;
if(pchIn == NULL)
{
return 0;
}
nLen = MultiByteToWideChar(CP_ACP, 0, pchIn, -1, NULL, 0);//取得所需缓存的多少
ptch = new WCHAR[nLen];//申请缓存空间
MultiByteToWideChar(CP_ACP, 0, pchIn, -1, ptch, nLen);//转码
pstrOut->Format(_T("%s"), ptch);
delete [] ptch;
return nLen;
}