随笔 - 170  文章 - 0  评论 - 16  阅读 - 35908 

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

 

posted on   北京开发  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示