分类: C/C++
2005-11-30 13:55:31
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