gbk字符集转为utf8字符集

发布时间 2023-08-11 16:58:24作者: 北京开发

#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

int encoding_convert(char *src_chset, char *to_chset, char *src_data, size_t inlen, char *tgt_data, int outlen)

{

        iconv_t cd;

        int rc;
        char **in_buf = &src_data;
        char **out_buf = &tgt_data;
        size_t conv_len = outlen;        

        cd = iconv_open(to_chset, src_chset);
        if(cd==0)
                return -1;
        memset(tgt_data, 0, outlen);
        if(iconv(cd, in_buf, &inlen, out_buf, &conv_len) == -1)
        {
                iconv_close(cd);
                return -1;
        }
        iconv_close(cd);

        return conv_len;
}

int main(int argc, char *argv[])
{
        FILE *fh;
        struct stat st;
        char *gbk_buf = NULL;
        char *utf8_buf = NULL;

        if(argc < 2)
                printf("\n./PROG file \n");
        if(stat(argv[1], &st) != 0)
        {
                printf("\n stat file error\n");
                return -1;
        }
        if(st.st_size <= 0)
        {
                printf("\n file size is 0, error\n");
                return -1;
        }

        fh = fopen(argv[1], "rb");
        if(fh == NULL)
        {
                printf("\n open file error\n");
        }
        gbk_buf = (char *)malloc(st.st_size + 1);
        if(gbk_buf == NULL)
        {
                printf("\nmalloc gbk buf error\n");
                return -1;
        }

        utf8_buf = (char *)malloc(st.st_size * 2 + 1);
        if(utf8_buf == NULL)
        {
                printf("\nmalloc utf buf error\n");
                return -1;
        }

        size_t rlen = fread(gbk_buf, 1, st.st_size, fh);
        if(rlen > 0)
        {
                printf("\nread len:%d \n", rlen);
                encoding_convert("gb2312", "utf-8", gbk_buf, rlen, utf8_buf, st.st_size * 2);
                printf("\nGBK data:%s \n", gbk_buf);
                printf("\nUTF8 data:%s \n", utf8_buf);
        }
        return 0;
}