CStdioFile在UNICODE环境下读取汉字

CStdioFile在UNICODE环境下读取汉字2009-08-05 17:45CStdioFile file;
     if (!file.Open(m_File_Path, CFile::modeRead)) return;
     CString strLine;


     while (file.ReadString(strLine))    
     { 
        //strLine处理
     }


问题:
     CStdioFile在_MSBC环境下读取任何ANSI文本数据都没问题,在UNICODE环境下读取ANSI文本中的中文时就会显示乱码。


原因:
     CStdioFile读取ANSI文本数据时按char类型读取,在_MSBC下可以直接填充到CString,在UNICODE环境下要先将char转换成宽字符WCHAR,然后再填充到CString,即一个汉字的两个char将变成两个UNICODE字符WCHAR。


解决办法:
     在UNICODE环境下file.ReadString(strLine)取得的数据实际上是char类型,但是存储在UNICODE字符串中。为了取得真实数据,必须对strLine进行处理。


void function(CString &str)
{
     char *szBuf = new char[str.GetLength()];


     for (int i = 0 ; i < str.GetLength(); i++)
     {
         szBuf[i] = str.GetAt(i);
     }
     CharToUnicode(szBuf , &str);


     delete []szBuf;
}
     注:此函数在编译的时候会提示
                 warning C4244: '=' : conversion from 'unsigned short' to 'char', possible loss of data
             不用管它,丢失的数据是我们不需要的。




===================================================================================


/
// 将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;
}




/
// 将Unicode字符转换为Char型字符
int UnicodeToChar(CString &strIn, char *pchOut, int nCharLen)
{
     if(pchOut == NULL)
     {
         return 0;
     }


     int nLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)strIn.GetBuffer(BUFFER_SIZE_KILO),-1, NULL, 0, NULL, NULL);
     nLen = min(nLen, nCharLen);
     WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)strIn.GetBuffer(BUFFER_SIZE_KILO), -1, pchOut,
         nLen, NULL, NULL);
    
     if(nLen < nCharLen)
     {
         pchOut[nLen] = 0;
     }


     return nLen;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值