UTF.COM.CN

c语言字符编码转换

作者:佚名 | 来源:网络 | 添加时间:2006-07-21 11:49:42 | 人气:6471

c语言字符编码转换

使用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/libi ... v/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/libi ... biconv/iconv.3.html

3.close.int iconv_close (iconv_t cd); http://www.gnu.org/software/libi ... /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:http://xcin.linux.org.tw/i18n/pc2000/p4/node2.html

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

责任编辑:冬天来了
【字号: 】【去论坛讨论】【发表评论】【打印本文】【告诉好友】【关闭窗口
网友评论(评论内容只代表网友观点,与本站立场无关!)

姓名:

验证码: 点击刷新