将ANSI编码装换为UTF-8在windows MFC环境下测试下面的代码
static int ansi2utf8(IN const char *cSrc, OUT char *cDest)
{
assert(NULL != cSrc && NULL != cDest);
int hResult = SUCCESS;
int nBufferLen = 0;
//MultiByteToWideChar
nBufferLen = MultiByteToWideChar(CP_ACP, 0, cSrc, -1, NULL, 0);
char *cTempBuffer = (char*)malloc(strlen(cSrc) * sizeof(WCHAR));
memset(cTempBuffer, 0, nBufferLen);
nBufferLen = MultiByteToWideChar(CP_ACP, 0, cSrc, -1, (LPWSTR)cTempBuffer, nBufferLen);
//WideCharToMultiByte 切勿想当然,参数个数与前一个函数不一样
nBufferLen = WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)cTempBuffer, -1,
NULL, 0, NULL, NULL);
cDest = (char*)realloc(cDest, nBufferLen);
memset(cDest, 0, nBufferLen);
nBufferLen = WideCharToMultiByte(CP_UTF8, 0,(LPWSTR)cTempBuffer, -1,
cDest, nBufferLen, NULL, NULL);
if(0 != nBufferLen)
hResult = SUCCESS;
return hResult;
}
//以下代码将UTF-8 转换为gb2312
intutf8togb2312(const char *sourcebuf, size_t sourcelen, char *destbuf, size_tdestlen)
{
iconv_t cd;
if( (cd = iconv_open("utf-8", "gb2312")) == 0) //查看相关函数,在Linux中使用locale -a命令查看字符集,转为其他字符集只 //需要改变该参数即可
{
return -1;
}
memset(destbuf,0,destlen);
const char **source = &sourcebuf;
char **dest = &destbuf; //想清楚,此处为什么要保存原始地址?
//注意:该函数回改变指针,如source会累加,调试运行观察source指针。
if((size_t)(-1) == iconv(cd, (char **)source, &sourcelen, dest,&destlen))
{
return -1;
}
iconv_close(cd);
return 0;
}