ºìÁªLinuxÃÅ»§
Linux°ïÖú

LinuxϱàÂëת»»c,c++ʵÏÖ

·¢²¼Ê±¼ä:2007-05-07 09:40:29À´Ô´:ºìÁª×÷Õß:Winterh
ÔÚLINUXÉϽøÐбàÂëת»»Ê±,¼È¿ÉÒÔÀûÓÃiconvº¯Êý×å±à³ÌʵÏÖ,Ò²¿ÉÒÔÀûÓÃiconvÃüÁîÀ´ÊµÏÖ,Ö»²»¹ýºóÕßÊÇÕë¶ÔÎļþµÄ,¼´½«Ö¸¶¨Îļþ´ÓÒ»ÖÖ±àÂëת»»ÎªÁíÒ»ÖÖ±àÂë¡£
Ò»¡¢ÀûÓÃiconvº¯Êý×å½øÐбàÂëת»»
iconvº¯Êý×åµÄÍ·ÎļþÊÇiconv.h,ʹÓÃÇ°Ðè°üº¬Ö®¡£
#include
iconvº¯Êý×åÓÐÈý¸öº¯Êý,Ô­ÐÍÈçÏÂ:
(1) iconv_t iconv_open(const char *tocode, const char *fromcode);
´Ëº¯Êý˵Ã÷½«Òª½øÐÐÄÄÁ½ÖÖ±àÂëµÄת»»,tocodeÊÇÄ¿±ê±àÂë,fromcodeÊÇÔ­±àÂë,¸Ãº¯Êý·µ»ØÒ»¸öת»»¾ä±ú,¹©ÒÔÏÂÁ½¸öº¯ÊýʹÓá£
(2) size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft);
´Ëº¯Êý´ÓinbufÖжÁÈ¡×Ö·û,ת»»ºóÊä³öµ½outbufÖÐ,inbytesleftÓÃÒԼǼ»¹Î´×ª»»µÄ×Ö·ûÊý,outbytesleftÓÃÒԼǼÊä³ö»º³åµÄÊ£Óà¿Õ¼ä¡£ (3) int iconv_close(iconv_t cd);
´Ëº¯ÊýÓÃÓڹرÕת»»¾ä±ú,ÊÍ·Å×ÊÔ´¡£
Àý×Ó1: ÓÃCÓïÑÔʵÏÖµÄת»»Ê¾Àý³ÌÐò

/* f.c : ´úÂëת»»Ê¾ÀýC³ÌÐò */
#include
#define OUTLEN 255
main()
{
char *in_utf8 = "æ­£å?¨å??è£?";
char *in_gb2312 = "ÕýÔÚ°²×°";
char out[OUTLEN];

//unicodeÂëתΪgb2312Âë
rc = u2g(in_utf8,strlen(in_utf8),out,OUTLEN);
printf("unicode-->gb2312 out=%sn",out);
//gb2312ÂëתΪunicodeÂë
rc = g2u(in_gb2312,strlen(in_gb2312),out,OUTLEN);
printf("gb2312-->unicode out=%sn",out);
}
//´úÂëת»»:´ÓÒ»ÖÖ±àÂëתΪÁíÒ»ÖÖ±àÂë
int code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int outlen)
{
iconv_t cd;
int rc;
char **pin = &inbuf;
char **pout = &outbuf;

cd = iconv_open(to_charset,from_charset);
if (cd==0) return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1;
iconv_close(cd);
return 0;
}
//UNICODEÂëתΪGB2312Âë
int u2g(char *inbuf,int inlen,char *outbuf,int outlen)
{
return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}
//GB2312ÂëתΪUNICODEÂë
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}

Àý×Ó2: ÓÃC++ÓïÑÔʵÏÖµÄת»»Ê¾Àý³ÌÐò

/* f.cpp : ´úÂëת»»Ê¾ÀýC++³ÌÐò */
#include
#include

#define OUTLEN 255

using namespace std;

// ´úÂëת»»²Ù×÷Àà
class CodeConverter {
private:
iconv_t cd;
public:
// ¹¹Ôì
CodeConverter(const char *from_charset,const char *to_charset) {
cd = iconv_open(to_charset,from_charset);
}

// Îö¹¹
~CodeConverter() {
iconv_close(cd);
}

// ת»»Êä³ö
int convert(char *inbuf,int inlen,char *outbuf,int outlen) {
char **pin = &inbuf;
char **pout = &outbuf;

memset(outbuf,0,outlen);
return iconv(cd,pin,(size_t *)&inlen,pout,(size_t *)&outlen);
}
};

int main(int argc, char **argv)
{
char *in_utf8 = "æ­£å?¨å??è£?";
char *in_gb2312 = "ÕýÔÚ°²×°";
char out[OUTLEN];

// utf-8-->gb2312
CodeConverter cc = CodeConverter("utf-8","gb2312");
cc.convert(in_utf8,strlen(in_utf8),out,OUTLEN);
cout << "utf-8-->gb2312 in=" << in_utf8 << ",out=" << out << endl;

// gb2312-->utf-8
CodeConverter cc2 = CodeConverter("gb2312","utf-8");
cc2.convert(in_gb2312,strlen(in_gb2312),out,OUTLEN);
cout << "gb2312-->utf-8 in=" << in_gb2312 << ",out=" << out << endl;
}
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ