新的轉碼方法 , libiconv , BIG5 轉 UTF8

Jack 大大寫好了這段 code , 很好用, 就貼在這兒了, 下次可以直接剪下跟貼上

重點有兩個:

1. From encoding 是 CP950

2. libiconv 不要用 libc 的, 因為缺一個 function : iconvctl

int fnConvert(const char *from, const char *to, char* save, int savelen, char *src, int srclen)
{
    iconv_t cd;
    char   *inbuf = src;
    char *outbuf = save;
    size_t outbufsize = savelen;
    int status = 0;
    size_t  savesize = 0;
    size_t inbufsize = srclen+1;
    char* inptr = inbuf;
    size_t      insize = inbufsize;
    char* outptr = outbuf;
    size_t outsize = outbufsize;

    if ( ( cd = iconv_open(to, from) ) == (iconv_t)-1 )
    {
        status = -1;
        goto done;
    }

    iconv(cd,NULL,NULL,NULL,NULL);
    if (inbufsize == 0)
    {
        status = -1;
        goto done;
    }
    while (insize > 0)
    {
        size_t res = iconv(cd, &inptr,&insize,&outptr,&outsize);
        if (outptr != outbuf)
        {
            int saved_errno = errno;
            int outsize = outptr - outbuf;
            strncpy(save+savesize, outbuf, outsize);
            errno = saved_errno;
        }
        if (res == (size_t)(-1))
        {
            if (errno == EILSEQ)
            {
                int one = 1;
                iconvctl(cd,ICONV_SET_DISCARD_ILSEQ,&one);
                status = -3;
            }
            else if (errno == EINVAL)
            {
                if (inbufsize == 0)
                {
                    status = -4;
                    goto done;
                }
                else
                {
                    break;
                }
            }
            else if (errno == E2BIG)
            {
                status = -5;
                goto done;
            }
            else
            {
                status = -6;
                goto done;
            }
        }
    }
    status = strlen(save);
done:
    iconv_close(cd);
    return status;
}

EXAMPLE:
int fnB2U( unsigned char *str )
{
    int srclen, destlen, status;
    unsigned char tmp[2048];

    status = -1;
    if ( ( srclen = strlen( str ) ) == 0 )
        return status;
    destlen  = sizeof( unsigned char ) * ( srclen * 2 ) + 1;
    tmp[0] = '';
    if ( ( status = fnConvert ( "CP950", "UTF-8", tmp, destlen, str, srclen) ) > 0 )
        strcpy( str, tmp);
    else
        printf( "status = %dn");
    return( status);
}

Comments are closed.

Related URL:
  1. Get MAC address using C
  2. [好文推薦] A TUTORIAL ON POINTERS AND ARRAYS IN C
  3. The Expat XML Parser – XML 分析/拆解工具 – C – 這個讚! 用 C 寫 spider 會用到
  4. Protected: Some Simple C Programs – 好用的 C 範例程式/片段
  5. get my ip address useing c / sample code
  6. 解決 error while loading shared libraries 的方法
  7. compile multiple source code