MFC项目采用Unicode编码,读取文本数据乱码转换函数

来源:互联网 发布:jquery.media.js 编辑:程序博客网 时间:2024/04/29 16:05

当MFC项目采用Unicode时,CStdioFile.ReadString读取到数据都是Unicode编码的,必须进行转换,不然就是乱码

// 字节数据转换成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);//CP_ACP是本地机器Local属性

//可以修改成指定语言GB2312 936. Shift-JIS 932 UTF-8 65001.
 ptch = new WCHAR[nLen];
 MultiByteToWideChar(CP_ACP, 0, pchIn, -1, ptch, nLen);
 pstrOut->Format(_T("%s"), ptch);

 delete [] ptch;

 return nLen;
}

实现CString的编码改变。使之能够显示成本地语言。

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

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

 delete []szBuf;
}

 

 

 

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

原创粉丝点击