使用iconv进行文件编码转换

在使用科大讯飞的时候输出字符是gbk字符编码。但是在ubuntu下gbk显示乱码,故用iconv进行字符编码转换。下面是我整理的字符编码转化的程序案例。从gbk2312转换到utf-8.

程序代码:

#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;
    unsigned char gb[]={0xd6,0xd0,0x00};

    cd = iconv_open("UTF-8", "GB2312");
    if (cd == (iconv_t)-1)
    {
        perror("iconv_open");
        exit(-1);
    }

    in = gb;
    out = buf;
    inlen = strlen(in);
    outlen = sizeof(buf);
    printf("in[ %s ]\n",in);
    printf("inlen [ %ld ]\n", inlen);

    n = iconv(cd, &in, &inlen, &out, &outlen);
    if (n == -1)
    {
        perror("iconv");
        exit(-1);
    }

    buf[ sizeof(buf)-outlen ] = 0;

    printf("out [ %s ]\n", buf);
    printf("outlen [ %ld ]\n", sizeof(buf)-outlen);

    iconv_close(cd);

    return 0;
}

 

posted @ 2017-01-13 10:15  叶念西风  阅读(262)  评论(0编辑  收藏  举报
叶念西风 - 个人博客 & 电脑Run - 维修帮助软件教程安装