/////////////////////////////////////////////////////// #include <iconv.h> #include <stdlib.h> #include <stdio.h> int code_convert(char *from_charset,char *to_charset,char *inbuf,size_t inlen,char *outbuf,size_t outlen) { iconv_t cd; int rc; char **pin = &inbuf; char **pout = &outbuf; cd = iconv_open(to_charset,from_charset); if (cd==0) return -1; if (iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1; iconv_close(cd); return 0; } // utf8码转为GB2312码 int u2g(char *inbuf,int inlen,char *outbuf,int outlen) { return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen); } // GB2312码转为utf8 int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen) { return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen); } // utf8转为gbk std::string u2a(const char *inbuf) { int inlen=strlen(inbuf); string strRet; strRet.resize(inlen*2+2); if(code_convert("utf-8","gbk",const_cast<char *>(inbuf),inlen,&strRet[0],strRet.size())) return inbuf; return strRet; } // gbk转为utf8 std::string a2u(const char *inbuf) { int inlen=strlen(inbuf); string strRet; strRet.resize(inlen*2+2); if(code_convert("gbk","utf-8",const_cast<char *>(inbuf),inlen,&strRet[0],strRet.size())) return inbuf; return strRet; }