蓝天

iconv_open、iconv和iconv_close函数使用示例

bool isUtf8(const char* str)
{
    return ((0xEF == (unsigned char)(str[0])) 
         && (0xBB == (unsigned char)(str[1])) 
         && (0xBF == (unsigned char)(str[2])));
}

int code_convert(char *from_charset,char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
    iconv_t cd;    
    char **pin = &inbuf;
    char **pout = &outbuf;
    
    cd = iconv_open(to_charset, from_charset);
    if (0 == cd) return -1;
    if (-1 == iconv(cd, pin, &inlen, pout, &outlen))
    {
        int old_errno = errno;
        iconv_close(cd);
        errno = old_errno;
        return -1;
    }

    iconv_close(cd);
    return 0;
}

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

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

posted on 2013-05-20 16:24  #蓝天  阅读(640)  评论(0编辑  收藏  举报

导航