字体转换器c语言代码大全,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/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

一个小例子:

/* 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; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值