字符编码转换

来源:互联网 发布:php转换时间戳函数 编辑:程序博客网 时间:2024/05/27 16:43

CStdioFile 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;
}

原创粉丝点击