linux下字符集编码转换(c++) [笔记,转载]

demo

#include <string.h>
#include <iconv.h>
#include <iostream>

using namespace std;

int code_convert(char *from_charset, char *to_charset, char *inbuf,int inlen,
                char *outbuf,int outlen)
{
    iconv_t cd;

    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open(to_charset,from_charset);
    if (cd == 0)
    {
        return -1;
    }
    memset(outbuf,0,outlen);
    std::size_t inlen_t = (std::size_t)inlen;
    std::size_t outlen_t = (std::size_t)outlen;
    if (iconv(cd,pin,&inlen_t,pout,&outlen_t) == -1)
    {
        return -1;
    }

    iconv_close(cd);

    return 0;
}


int gb2312ToUtf8(char *inbuf,int inlen,char *outbuf,int outlen)
{
    return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}

string gb2312ToUtf8(char *inbuf)
{
    if (NULL == inbuf)
    {
        return string("");
    }

    char errmsg[256] = { 0 };
    gb2312ToUtf8(inbuf,strlen(inbuf),errmsg,256);

    return string(errmsg);
}


int main(int argc, char *argv[])
{
    char *str = "中文";
    string s = gb2312ToUtf8(str);
    cout << "s: " << s << endl;

    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值