C++ GBK to UTF8

Published on Friday, February 18, 2011

GBK to UTF8 xmwen@126.com

char *gbk2utf8(const char *strGBK){
int len;
wchar_t *strUnicode;
char *strUTF8;
if (!strGBK){return NULL;}
len = MultiByteToWideChar(CP_GBK, 0,strGBK, -1, NULL,0);
if (len <1){return NULL;}
strUnicode = (wchar_t *) malloc(sizeof(wchar_t) * len);
if (!strUnicode){return NULL;}
len = MultiByteToWideChar(CP_GBK, 0, strGBK, -1, strUnicode, len);
if (len<1){free(strUnicode);return NULL;}
len = WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, NULL, 0, NULL, NULL);
if (len<1){free(strUnicode);return NULL;}
strUTF8 = (char *) malloc(sizeof(char) * len);
if (!strUTF8){free(strUnicode);return NULL;}
len = WideCharToMultiByte (CP_UTF8, 0, strUnicode, -1, strUTF8, len, NULL,NULL);
free(strUnicode);
if (len<1){free(strUTF8);return NULL;}
return strUTF8;
}