Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4826211
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2010-04-13 13:42:11

#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;    
}
    

 

可以看看这个

http://www.gnu.org/software/libiconv/documentation/libiconv/

阅读(3264) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~