C語言字元編碼處理

來源:互聯網
上載者:User

標籤:

一、簡介

由於曆史原因,國際化的文字常常由於語言或者國家的原因使用不同的編碼。libiconv庫為需要做轉換的應用提供了一個iconv()的函數,以實現一個字元編碼到另一個字元編碼的轉換。

 

二、安裝

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

 

三、API

iconv函數族有三個函數,原型如下:

iconv_t iconv_open(const char *tocode, const char *fromcode);

此函數說明將要進行哪兩種編碼的轉換,tocode是目標編碼,fromcode是原編碼,該函數返回一個轉換控制代碼,供以下兩個函數使用。

 

size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft);

此函數從inbuf中讀取字元,轉換後輸出到outbuf中,inbytesleft用以記錄還未轉換的字元數,outbytesleft用以記錄輸出緩衝的剩餘空間。

 

int iconv_close(iconv_t cd);

此函數用於關閉轉換控制代碼,釋放資源。

 

四、執行個體

參考:

http://www.linuxidc.com/Linux/2014-11/109066.htmhttp://www.cnblogs.com/lancidie/archive/2013/04/12/3016965.html

 

example1.c

#include<stdio.h>                                                                                                                                        #include <string.h>#include <iconv.h>int ChangeCode( const char* pFromCode,        const char* pToCode,        const char* pInBuf,        size_t* iInLen,        char* pOutBuf,        size_t* iOutLen );int main( int argc, char* argv[] ){    char sInBuf[100];    char sOutBuf[100];    size_t iInLen = 0;    size_t iOutLen = 100;    int iRet;    strcpy( sInBuf, "測試 Test Source" );    puts(sInBuf);    memset( sOutBuf, 0x00, 100 );    iInLen = strlen( sInBuf );    iRet = ChangeCode( "GBK", "UTF-16", sInBuf, &iInLen, sOutBuf, &iOutLen );    puts(sOutBuf);    iRet = ChangeCode( "UTF-16", "GBK", sOutBuf, &iOutLen , sOutBuf, &iOutLen );    puts(sOutBuf);    return 0;}int ChangeCode( const char* pFromCode,        const char* pToCode,        const char* pInBuf,        size_t* iInLen,        char* pOutBuf,        size_t* iOutLen ){    int iRet;    //開啟字元集轉換    iconv_t hIconv = iconv_open( pToCode, pFromCode );    if ( -1 == (int)hIconv )    {        return -1;//開啟失敗,可能不支援的字元集    }    //開始轉換    iRet = iconv( hIconv, (const char**)(&pInBuf), iInLen, (char**)(&pOutBuf), iOutLen );    //關閉字元集轉換    iconv_close( hIconv );    return iRet;}

編譯

gcc -g -o example1 example1.c  -liconv

運行

C語言字元編碼處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.