Use functions in Linux C to create Chinese directories and files. The encoding format of strings must be UTF-8.
For example, you want to use int mkdir (const char * pathname, mode_t mode); To create a Chinese directory. The pathname encoding format must be UTF-8 instead of gb3212/GBK. Otherwise, it is garbled.
In Linux C, how does one perform GBK <----> UTF-8 encoding conversion? The iconv function cluster is used.
# Include <iconv. h> </P> <p> int code_convert (char * from_charset, char * to_charset, char * inbuf, int inlen, char * outbuf, int outlen) <br/>{< br/> iconv_t CD; <br/> int RC; <br/> char ** pin = & inbuf; <br/> char ** pout = & outbuf; </P> <p> Cd = iconv_open (to_charset, from_charset); <br/> If (Cd = 0) <br/> return-1; <br/> memset (outbuf, 0, outlen); <br/> If (iconv (Cd, pin, & inlen, pout, & outlen) =-1) <br/> return-1; <br/> iconv_close (CD); <br/> return 0; <br/>}</P> <p> int u2g (char * inbuf, int inlen, char * outbuf, int outlen) <br/>{< br/> return code_convert ("UTF-8", "gb2312", inbuf, inlen, outbuf, outlen ); <br/>}</P> <p> int g2u (char * inbuf, size_t inlen, char * outbuf, size_t outlen) <br/>{< br/> return code_convert ("gb2312", "UTF-8", inbuf, inlen, outbuf, outlen); <br/>}< br/>
Where
The header file of the iconv function family is iconv. H, which must be included before use.
# Include <iconv. h>
The iconv function family has three functions. The prototype is as follows:
(1) 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.
(2) 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.
(3) int iconv_close (iconv_t CD );
This function is used to close the conversion handle and release resources.