C character encoding, character encoding
I. Introduction
For historical reasons, international texts often use different encodings for language or country reasons. The libiconv Library provides an iconv () function for the application to convert one character encoding to another.
Ii. Installation
http://www.gnu.org/software/libiconv/
Iii. API
The iconv function family has three functions. The prototype is as follows:
iconv_t iconv_open(const char *tocode, const char *fromcode);
This function indicates which two types of encoding are to be converted. tocode is the target encoding and fromcode is the original encoding. This function returns a conversion handle for the following two functions.
size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft);
This function reads characters from inbuf and outputs the converted characters to outbuf. inbytesleft records the number of characters that have not been converted, and outbytesleft records the remaining space of the output buffer.
int iconv_close(iconv_t cd);
This function is used to close the conversion handle and release resources.
Iv. Instances
Refer:
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; // enable character set conversion iconv_t hIconv = iconv_open (pToCode, pFromCode); if (-1 = (int) hIconv) {return-1; // opening failed, unsupported Character Set} // begin to convert iRet = iconv (hIconv, (const char **) (& pInBuf), iInLen, (char **) (& pOutBuf ), iOutLen); // disable Character Set conversion iconv_close (hIconv); return iRet ;}
Compile
gcc -g -o example1 example1.c -liconv
Run