#include <stdio.h> #include <iconv.h> #include <string.h>
#define LEN 10 int code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int outlen) { iconv_t cd; char **pin = &inbuf; char **pout = &outbuf;
cd = iconv_open(to_charset,from_charset); if (cd==0) return -1; memset(outbuf,0,outlen); if (iconv(cd,pin,(size_t* __restrict__)(&inlen),pout,(size_t* __restrict__)(&outlen))==-1) return -1; iconv_close(cd); return 0; }
//UNICODE码转为GB2312码
int u2g(char *inbuf,int inlen,char *outbuf,int outlen) { return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen); } //GB2312码转为UNICODE码
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen) { return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen); }
//big5码转为utf8码
int b2u(char *inbuf,int inlen,char *outbuf,int outlen) { return code_convert("BIG5","utf-8",inbuf,inlen,outbuf,outlen); } //utf8码转为big5码
int u2b(char *inbuf,size_t inlen,char *outbuf,size_t outlen) { return code_convert("utf-8","BIG5",inbuf,inlen,outbuf,outlen); }
int main(int argc, char** argv) { char* utf8 = argv[1]; int len = LEN; char b_buf[LEN] = {'\0'}; char u_buf[LEN] = {'\0'}; char g_buf[LEN] = {'\0'};
printf("utf8 is %s\n", utf8); u2g(utf8,strlen(utf8),g_buf,len);
printf("gb2312 is %s\n", g_buf); g2u(g_buf,strlen(g_buf),u_buf,len); printf("utf-8 is %s\n", u_buf);
if(u2b(utf8, strlen(utf8), b_buf, len)==-1) { printf("%s\n", "u2b error"); return -1; } printf("big5 is %s\n", b_buf); b2u(b_buf, strlen(b_buf), u_buf,len); printf("utf-8 is %s\n", u_buf); return 0; }
|