2 qq 30084517 qq_30084517 于 2016.09.24 18:51 提问

C++使用FILE类保存的数据乱码

图片说明
txt文件是UTF-8的,改为ANSI可以,但是能不能不改文件编码,程序解决?

1个回答

qq_30084517
qq_30084517   2016.09.24 21:02
已采纳

如果原字符是Unicode编码,使用WideCharToMultiBytes,使用UTF8代码页

如果是ansi编码的则先使用MultiBytesToWideChar转换为Unicode编码,再按上述操作完成
//把utf8转成unicode,再转成cstring

void ConvertUTF8ToANSI(char* strUTF8,CString &strANSI) //

{

int nLen = ::MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,(LPCTSTR)strUTF8,-1,NULL,0);  //返回需要的unicode长度  

WCHAR * wszANSI = new WCHAR[nLen+1];  

memset(wszANSI, 0, nLen * 2 + 2);  

nLen = MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUTF8, -1, wszANSI, nLen);    //把utf8转成unicode  



nLen = WideCharToMultiByte(CP_ACP, 0, wszANSI, -1, NULL, 0, NULL, NULL);        //得到要的ansi长度  

char *szANSI=new char[nLen + 1];  

memset(szANSI, 0, nLen + 1);  

WideCharToMultiByte (CP_ACP, 0, wszANSI, -1, szANSI, nLen, NULL,NULL);          //把unicode转成ansi  

strANSI = szANSI;  

delete wszANSI;  

delete szANSI;  

}

void ConvertANSIToUTF8(CString &strANSI)

{

int nLen = ::MultiByteToWideChar(CP_ACP,MB_ERR_INVALID_CHARS,(LPCTSTR)strANSI,-1,NULL,0);

unsigned short * wszUTF_8 = new unsigned short[nLen+1];

memset(wszUTF_8, 0, nLen * 2 + 2);

nLen = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strANSI, -1, wszUTF_8, nLen);

nLen = WideCharToMultiByte(CP_UTF8, 0, wszUTF_8, -1, NULL, 0, NULL, NULL);

char *szUTF8=new char[nLen + 1];  

memset(szUTF8, 0, nLen + 1);  

WideCharToMultiByte (CP_UTF8, 0, wszUTF_8, -1, szUTF8, nLen, NULL,NULL);  

strANSI = szUTF8;

delete wszUTF_8;

delete szUTF8;

}

Csdn user default icon
上传中...
上传图片
插入图片