{
if(lpUTF8Str == NULL) return -1;
int nRetLen = 0;
//获取转换到Unicode编码后所需要的字符空间长度
nRetLen = ::MultiByteToWideChar(CP_UTF8, 0,
WCHAR *lpUnicodeStr = new WCHAR[nRetLen + 1];
//转换到Unicode编码
nRetLen = ::MultiByteToWideChar(CP_UTF8, 0,
if(!nRetLen)
{
delete []lpUnicodeStr; return -1;
}
//获取转换到GBK编码后所需要的字符空间长度
nRetLen = ::WideCharToMultiByte(CP_ACP, 0, lpUnicodeStr,
CHAR *lpGBKStr = new CHAR[nRetLen + 1];
nRetLen = ::WideCharToMultiByte(CP_ACP, 0, lpUnicodeStr,
if(!nRetLen)
{
delete []lpUnicodeStr;
delete []lpGBKStr;
return -2;
}
str = lpGBKStr;
delete []lpUnicodeStr;
delete []lpGBKStr;
return 0;
}
此函数说明将要进行哪两种编码的转换,tocode是目标编码,fromcode是原编码,该函数返回一个转换句柄,供以下两个函数使用。
此函数从inbuf中读取字符,转换后输出到outbuf中,inbytesleft用以记录还未转换的字符数,outbytesleft用以记录输出缓冲的剩余空间。
此函数用于关闭转换句柄,释放资源。
#include <iconv.h>
#include <string.h>
#define BUFLEN 256
char outbuf[BUFLEN];
char inbuf[BUFLEN] = "characters convertion";
int main()
{
char *pin = inbuf;
char *pout = outbuf;
int inlen = strlen(pin);
int outlen = BUFLEN;
int retsize;
iconv_t cd;
cd = iconv_open("UTF-8", "GBK");
if((iconv_t)-1 == cd) {
perror("iconv_open error");
return -1;
}
retsize = iconv(cd, &pin, (size_t *)&inlen, &pout, (size_t *)&outlen);
if((size_t)-1 == retsize) {
perror("iconv error");
return -2;
}
if(outlen > 0) {
printf("%s\n", outbuf);
}
iconv_close(cd);
return 0;
}