在Linux下寫C程式,尤其是網路通訊程式時經常遇到編碼轉換的問題,這裡要用到iconv函式庫。

iconv函式庫有以下三個函式

1
2
3
4
5
6
#include <iconv.h>
iconv_t iconv_open(const char *tocode, const char *fromcode); //return (iconv_t)-1 if failed
size_t iconv(iconv_t cd,
char **inbuf, size_t *inbytesleft,
char **outbuf, size_t *outbytesleft); //return (size_t)-1 if failed
int iconv_close(iconv_t cd); //return -1 if failed

這三個函式的功能顯而易見,分別是開啟一個iconv_t控制代碼,轉換字串以及關閉一個iconv_t控制代碼。其中有必要一說的是iconv函式,這個函式十分容易用錯。

iconv函式的五個引數中,第一個引數是iconv控制代碼,第二、三個引數是需要轉換的字串的地址和長度的地址,第四、五個引數是儲存結果的字串的地址和長度的地址,注意這裡傳的都是地址,因為這四個引數的值都有會被iconv函式改變。iconv會逐步的將*inbuf中的字元轉換到*outbuf中,並增加*inbuf指標減少*inbytesleft的值,以及增加*outbuf指標減少*outbytesleft的值。

iconv函式會因為以下四種原因停止並返回:

  1. *input中遇到了一個非法的多位元組序列,返回(size_t)-1並置errno=EILSEQ,返回時*inbuf指向非法字元的開頭。
  2. *input全部轉換完,返回不可轉換的字元數。
  3. *input中遇到了一個不完整的多位元組序列,返回(size_t)-1並置errno=EINVAL,返回時*inbuf指向不完整字元的開頭。
  4. *output空間不夠,返回(size_t)-1並置errno=E2BIG。

以下給出一個示例函式,將一個字串從utf-8轉換成gbk後再重新轉換成utf-8。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iconv.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h> int charset_convert(const char *from_charset, const char *to_charset,
char *in_buf, size_t in_left, char *out_buf, size_t out_left) {
iconv_t icd;
char *pin = in_buf;
char *pout = out_buf;
size_t out_len = out_left;
if ((iconv_t)-1 == (icd = iconv_open(to_charset,from_charset))) {
return -1;
}
if ((size_t)-1 == iconv(icd, &pin, &in_left, &pout, &out_left)) {
iconv_close(icd);
return -1;
}
out_buf[out_len - out_left] = 0;
iconv_close(icd);
return (int)out_len - out_left;
} int main(int argc, char *argv[]) {
char *from_str = "你好,中南。- Hello, CSU.";
char *to_str_gbk, *to_str_utf8;
int len;
//utf-8 => gbk
to_str_gbk = (char*)calloc(1, strlen(from_str) * 3);
if (-1 == (len = charset_convert("UTF-8", "GB2312", from_str,
strlen(from_str), to_str_gbk, strlen(from_str) * 3))) {
perror("UTF8=>GBK error");
}
//gbk => utf8
to_str_utf8 = (char*)calloc(1, len * 3);
if (-1 == (len = charset_convert("GB2312", "UTF-8", to_str_gbk,
len, to_str_utf8, len * 3))) {
perror("GBK=>UTF8 error");
}
//output
printf("original : %s\n", from_str);
printf("to gbk : %s\n", to_str_gbk);
printf("gbk to utf8: %s\n", to_str_utf8);
}

我用的xshell連線到虛擬機器,先將terminal的編碼設定為utf-8執行,結果如下

1
2
3
original   : 你好,中南。- Hello, CSU.
to gbk : ţºã¬אŏ¡£- Hello, CSU.
gbk to utf8: 你好,中南。- Hello, CSU.

再將terminal的編碼設定為gbk執行,結果如下

1
2
3
original   : 浣犲ソ錛屼腑鍗椼€? Hello, CSU.
to gbk : 你好,中南。- Hello, CSU.
gbk to utf8: 浣犲ソ錛屼腑鍗椼€? Hello, CSU.

可見,在相應的編碼下,對應的字串能正常顯示。

http://vimersu.win/blog/2014/03/04/linux-iconv/