Linux C++ gbk转为utf-8

来源:互联网 发布:gov是什么域名 编辑:程序博客网 时间:2024/06/05 08:10

linux下没有上面的两个函数,需要使用函数 mbstowcs和wcstombs

mbstowcs将多字节编码转换为宽字节编码

wcstombs将宽字节编码转换为多字节编码

这两个函数,转换过程中受到系统编码类型的影响,需要通过设置来设定转换前和转换后的编码类型。通过函数setlocale进行系统编码的设置。

linux下输入命名

locale -a查看系统支持的编码类型。

andy@andy-linux:~$ locale -a
c
en_ag
en_au.utf8
en_bw.utf8
en_ca.utf8
en_dk.utf8
en_gb.utf8
en_hk.utf8
en_ie.utf8
en_in
en_ng
en_nz.utf8
en_ph.utf8
en_sg.utf8
en_us.utf8
en_za.utf8
en_zw.utf8
posix
zh_cn.gb18030
zh_cn.gbk
zh_cn.utf8
zh_hk.utf8
zh_sg.utf8
zh_tw.utf8

本例子中实现的是由zh_CN.gbk到zh_CN.utf8的转换

流程:

1、调用函数setlocale(LC_ALL,"zh_CN.gbk"),设置待转码的字符串类型为gbk类型。

2、调用函数mbstowcs,实现 1  设置的编码到unicode编码的转换。

3、调用函数setlocale(LC_ALL,"zh_CN.utf8"),设置转换后编码类型为utf8类型。

4、调用函数wcstombs,实现unicode到 设置的编码类型的转换。
下面是我写的源码

</pre><pre name="code" class="cpp">#include <stdlib.h>#include <locale.h>/****************************************************************************** * function: gbk2utf8 * description: 实现由gbk编码到utf8编码的转换  *  * input: utfstr,转换后的字符串;  srcstr,待转换的字符串; maxutfstrlen, utfstr的最            大长度 * output: utfstr * returns: -1,fail;>0,success *  * modification history * -------------------- *  2011-nov-25, lvhongya written * -------------------- ******************************************************************************/int gbk2utf8(char *utfstr,const char *srcstr,int maxutfstrlen){    if(null==srcstr)    {        printf("bad parameter\n");        return -1;    }    //首先先将gbk编码转换为unicode编码    if(null==setlocale(lc_all,"zh_cn.gbk"))//设置转换为unicode前的码,当前为gbk编码    {        printf("bad parameter\n");        return -1;    }    int unicodelen=mbstowcs(null,srcstr,0);//计算转换后的长度    if(unicodelen<=0)    {        printf("can not transfer!!!\n");        return -1;    }    wchar_t *unicodestr=(wchar_t *)calloc(sizeof(wchar_t),unicodelen+1);    mbstowcs(unicodestr,srcstr,strlen(srcstr));//将gbk转换为unicode        //将unicode编码转换为utf8编码    if(null==setlocale(lc_all,"zh_cn.utf8"))//设置unicode转换后的码,当前为utf8    {        printf("bad parameter\n");        return -1;    }    int utflen=wcstombs(null,unicodestr,0);//计算转换后的长度    if(utflen<=0)    {        printf("can not transfer!!!\n");        return -1;    }    else if(utflen>=maxutfstrlen)//判断空间是否足够    {        printf("dst str memory not enough\n");        return -1;    }    wcstombs(utfstr,unicodestr,utflen);    utfstr[utflen]=0;//添加结束符    free(unicodestr);    return utflen;


0 0
原创粉丝点击