Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2590412
  • 博文数量: 351
  • 博客积分: 76
  • 博客等级: 上将
  • 技术积分: 3555
  • 用 户 组: 普通用户
  • 注册时间: 2004-11-13 21:27
文章分类

全部博文(351)

文章存档

2013年(1)

2012年(4)

2011年(7)

2010年(16)

2009年(34)

2008年(34)

2007年(34)

2006年(68)

2005年(82)

2004年(71)

分类: C/C++

2005-11-30 13:55:31

使用libiconv. 本文包括libiconv实用简单介绍及几个例子程序。

libiconv实用非常简单,只有3步:

1.使用 conv_t iconv_open (const char* tocode, const char* fromcode); 打开描述符。 fromcode和tocode为编码类型。conv_open的详细介绍看man iconv_open http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_open.3.html

2.使用 size_t iconv (iconv_t cd, const char* * inbuf, size_t * inbytesleft, char* * outbuf, size_t * outbytesleft); 进行编码转换。详细介绍看man 3 iconv。 http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.3.html

3.close.int iconv_close (iconv_t cd); http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_close.3.html

一个小例子:

/* lanconv.c - a simple example to convert GB2312 to UTF-8/BIG5 * * Author: zhou_weicheng at 163 dot com * Date: 2005/11/30 */ #include stdio.h #include stdlib.h #include string.h #include iconv.h int main(int argc, char *argv[]) { iconv_t cd; size_t n, inlen, outlen; char buf[1024]; char *in, *out; // cd = iconv_open("UTF-8", "GB2312"); cd = iconv_open("BIG5", "GB2312"); if (cd == (iconv_t)-1) { perror("iconv_open"); exit(-1); } in = argv[1]; out = buf; inlen = strlen(in); outlen = sizeof(buf); n = iconv(cd, &in, &inlen, &out, &outlen); if (n == -1) { perror("iconv"); exit(-1); } printf("%s ", buf); iconv_close(cd); exit(0); }

一个例子from:

 #include stdio.h #include string.h #include iconv.h int main(int argc, char **argv) { FILE *fin, *fout; char *encFrom, *encTo; char bufin[1024], bufout[1024], *sin, *sout; int mode, lenin, lenout, ret, nline; iconv_t c_pt; if (argc != 5) { printf("Usage: a.out "); return 0; } encFrom = argv[1]; encTo = argv[2]; if ((fin = fopen(argv[3], "rt")) == NULL) { printf("Cannot open file: %s ", argv[3]); return -1; } if ((fout = fopen(argv[4], "wt")) == NULL) { printf("Cannot open file: %s ", argv[4]); return -1; } if ((c_pt = iconv_open(encTo, encFrom)) == (iconv_t)-1) { printf("iconv_open false: %s ==> %s ", encFrom, encTo); return -1; } iconv(c_pt, NULL, NULL, NULL, NULL); nline = 0; while (fgets(bufin, 1024, fin) != NULL) { nline ++; lenin = strlen(bufin) + 1; lenout = 1024; sin = bufin; sout = bufout; ret = iconv(c_pt, &sin, &lenin, &sout, &lenout); printf("%s -> %s: %d: ret=%d, len_in=%d, len_out=%d ", encFrom, encTo, nline, ret, lenin, lenout); if (ret == -1) { printf("stop at: %s ", sin); break; } fprintf(fout, "%s", bufout); } iconv_close(c_pt); fclose(fin); fclose(fout); return 0; }

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