在网上有如下代码:
/*代码转换:从一种编码转为另一种编码*/
int code_convert(const char *from_charset, const char *to_charset, const char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
iconv_t cd;
int rc;
char **pin = ( char ** ) &inbuf;
char **pout = &outbuf;
cd = iconv_open(to_charset,from_charset);
if (cd==0) return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen)==-1)
return -1;
iconv_close(cd);
return 0;
}
/*UNICODE码转为GB2312码*/
int u2g(const char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}
/*GB2312码转为UNICODE码*/
int g2u(const char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}
如果遇到iconv转换异常,可用perror("iconv")来查看错误提示,以上代码我在FreeBSD下进行utf-8 -> gb2312转换失败,原因是iconv_open的两个参数都是小写的,而通过man iconv或iconv -l看到iconv支持的所有编码字符串均为大写。
阅读(7264) | 评论(0) | 转发(0) |