iconv c++ 编码转换

c++ GBK 转UTF-8

返回的ret如果是(size_t)(-1)那么就是出错了,否则就是0,成功了

iconv的返回值的类型是size_t(unsigned __int64 ),在windows上是8个字节。

我们用unsigned long long 来接是完全可以的。

#include <iconv.h>

int EncodeChange(char* input, size_t charInPutLen, char* output, size_t charOutPutLen, char *from_encode, char* to_encode);
int EncodeChange(const string& input, string& output, string from_encode, string to_encode);

int EncodeChange(char* input, size_t charInPutLen, char* output, size_t charOutPutLen, char *from_encode, char* to_encode)
{
    int ret =0;
    iconv_t cd;
    cd = iconv_open(to_encode, from_encode);
    ret = iconv(cd, &input, &charInPutLen, &output, &charOutPutLen);
    iconv_close(cd);
    return ret;
}

int EncodeChange(const string& input, string& output, string from_encode, string to_encode)
{
    int ret =0;
    size_t charInPutLen = input.length();
    if( charInPutLen == 0)
        return 0;
    char *pSource =(char *)input.c_str();
    size_t charOutPutLen = 2*charInPutLen;
    char *pTemp = new char[charOutPutLen];
    memset(pTemp,0,2*charInPutLen);

    iconv_t cd;
    char *pOut = pTemp ;
    cd = iconv_open(to_encode.c_str(), from_encode.c_str());
    ret = iconv(cd, &pSource, &charInPutLen, &pTemp, &charOutPutLen);
    iconv_close(cd);
    output = pOut;
    delete []pOut;//注意这里,不能使用delete []pTemp, iconv函数会改变指针pTemp的值
    return ret;
}



文章目录