2010年10月29日星期五

在linux下字符串编码之间的转换 (C/C++语言)

在ubuntu下运行通过..

int code_conver( const char *from_charset, const 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 );

if ( iconv( cd, pin, (size_t *)&inlen, pout, (size_t *)&outlen ) == -1 )
return -1;

iconv_close( cd );

return 0;

}

/*
* 参数iLen为字符串pszGBK分配的长度
* 随便设置iLen, 例如设置为10001, 远大于pszGBK分配的长度,在运行code_conver函数iconv语句时时会出错
* 同样, 也可以很方便地将GBK转换为utf8格式等等
*/
void fnUtf82GBK( char *pszUtf8, char *pszGBK, int iLen )
{
int iResult;
iResult = code_conver( "utf-8", "gb2312", pszUtf8, strlen( pszUtf8 ), pszGBK, iLen );
}