下面的範例簡單又清楚

來源 http://ashotw.blogspot.com/2008/08/iconv.html

 

咳咳...在Linux的環境下,一想到轉碼,就會想到iconv!

對iconv,小弟都只聞其名、未深入體驗,這次剛好有個機會來嘗試。試著寫個簡單的小範例來轉換字串成UTF-8或是Big5。

PS:因為blogger不知道要怎麼顯示 <> 這樣的符號(會被辨試成delimiter),所以改用 "" 表示。


#include "iconv.h"
#include "string.h"
#include "stdlib.h"
#include "errno.h"

int main( int argc, char **argv )
{
iconv_t cd;
size_t in_s, out_s;

/* UTF-8 轉 Big5 */
cd = iconv_open("BIG-5", "UTF8");

char *ibuf = "我是阿信", *in_ptr;
char *obuf = NULL, *out_ptr;

in_s = strlen(ibuf);
in_ptr = ibuf;

obuf = malloc( in_s * 3 );
out_s = in_s * 3;
out_ptr = obuf;

if( cd == (iconv_t )-1 ){
fprintf( stderr, "error opening iconv \n" );
exit(1);
}

if( iconv( cd, &in_ptr, &in_s, &out_ptr, &out_s) == -1 ){
printf("errno: %s\n", strerror(errno));
}

*out_ptr = '\0';
printf("%s, %s\n",ibuf, obuf);

iconv_close( cd );
free( obuf );
return 0;
}

接下來就 gcc -Wall a.c -o a.out,開一個Big5的terminal,執行一下這個新生的a.out,就能看到轉換後的字串了。

arrow
arrow
    全站熱搜

    mybeauty 發表在 痞客邦 留言(0) 人氣()