http://www.jollen.org/blog/2006/09/libiconv_1.html
 

libiconv: 字元集碼編轉換

jollen 發表於 September 27, 2006 11:10 PM

實作 Linux 系統程式時,常需要做「Unicode 與 Big5」間的字元編碼轉換;嵌入式 Linux 的應用也經常會遇到這樣的需求,例如我們原則上會將文件存成 Unicode,當程式執行時,再決定要輸出成 Unicode 或 Big5 (or GBxxxx),這時就要使用到 GNU 的 libiconv 專案。

GNU libiconv 用來做字元間的編碼轉換,已經廣泛被使用在 GNU/Linux 系統中,例如 PHP 的 iconv 系統即是使用 GNU libiconv。libiconv 要移植到 ARM9 平臺上也是非常容易的。GNU libiconv 的官方首頁是: http://www.gnu.org/software/libiconv/

把 libiconv 套件解開並編譯後,可以在 src/ 目錄下找到 iconv 執行檔,這是 libiconv 為我們寫好的一個字元轉碼 (conversion) 工具,這個工具相當的實用,比如以 jollen 的網站來說,jollen.org 的網頁是以 unicode 儲存,但是我們發佈的頁面是以 big5 編碼為主,我們所使用的轉換工具便是 iconv。

iconv 的使用可以參考 http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html,我們舉一個例子來說明,比如我想把 big5.txt 文件 (Big5 encode) 轉換成 Unicode (UTF-8),那麼只要執行:

$ iconv -f BIG5 -t UTF-8 big5.txt

就可以了,參數 -f 指定來源編碼,參數 -t 指定目的編碼,編碼後的字串會輸出到 stdout。字元集 BIG5 也可以寫成 BIG-5,或是 BIG-FIVE,或是 BIGFIVE;要怎麼知道 iconv 可以處理 (接受) 哪些字元集 (character set ),只要執行 'iconv -l' 就可以查詢了,輸出結果會是一大票的字元集列表。

這是使用 iconv 工具的方式,假如要自己寫程式的話也是非常簡單的,因為 libiconv 裡頭只有 3 個函數:

iconv_t iconv_open (const char* tocode, const char* fromcode):開啟 libiconv。
size_t iconv (iconv_t cd, const char* * inbuf, size_t * inbytesleft, char* * outbuf, size_t * outbytesleft):執行轉碼。
int iconv_close (iconv_t cd):做完轉碼後關閉 libiconv。

libiconv-1.xx/src/iconv.c 本身就是一個很棒的範例了,大家可以參考。

 

 

 

 

官方網址

http://www.gnu.org/software/libiconv/

最後版本

http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz

 

 

編譯~~我改編譯為靜態LIB

echo "configure"
./configure --enable-static=yes --enable-shared=no > configure.log

echo "make"
make > mak.log
 
echo "copy lib"

cp -rf include/iconv.h        ../
cp -rf lib/.libs/libiconv.a    ../

 

 

 

編譯遇到問題
http://www.linuser.com/thread-1482-1-1.html

  1. In file included from progname.c:26:0:
  2. ./stdio.h:1010:1: error: ‘gets’ undeclared here (not in a function)
  3. _GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");

查找 stion.in.h

查找 gets 找到698 行,将其和695行一註解掉:

  1. 695 /* It is very rare that the developer ever has full control of stdin,
  2. 696    so any use of gets warrants an unconditional warning.  Assume it is
  3. 697    always declared, since it is required by C89.
  4. 698 _GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");*/

下面加上下三面三行:

  1. #if defined(__GLIBC__) && !defined(__UCLIBC__) && !__GLIBC_PREREQ(2, 16)
  2. _GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");
  3. #endif

保存退出!

 

 

 

arrow
arrow
    文章標籤
    libiconv .
    全站熱搜

    立你斯 發表在 痞客邦 留言(0) 人氣()