字符集(编码)转换_Linux
ZC: 来自 我的项目 czgj
1、代码:
#include <stdio.h> #include <iconv.h> #include <string.h> //#pragma comment(lib, "iconv.lib") // ZC: 改放到 .pro文件中“LIBS += -liconv” /* //此函数说明将要进行哪两种编码的转换,tocode是目标编码,fromcode是原编码,该函数返回一个转换句柄,供以下两个函数使用。 (1) iconv_t iconv_open(const char *tocode, const char *fromcode); //此函数从inbuf中读取字符,转换后输出到outbuf中,inbytesleft用以记录还未转换的字符数,outbytesleft用以记录输出缓冲的剩余空间。 (2) size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft); //此函数用于关闭转换句柄,释放资源。 (3) int iconv_close(iconv_t cd); */ // - - - - - - - 以下是在Linux上实现的字符集转换函数 //int code_convert(char *from_charset,char *to_charset,const char *inbuf, size_t inlen,char *outbuf, size_t outlen) int code_convert(char *from_charset,char *to_charset, char *inbuf, size_t inlen,char *outbuf, size_t outlen) { iconv_t cd; //const char **pin = &inbuf; 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)==((size_t)-1)) return -1; iconv_close(cd); return 0; } /* UTF-8 to UTF-16 */ //int u2g(const char *inbuf, size_t inlen, char *outbuf, size_t outlen) int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("UTF-8","UTF-16",inbuf,inlen,outbuf,outlen); } /* UTF-16 to UTF-8 */ //int g2u(const char *inbuf, size_t inlen, char *outbuf, size_t outlen) int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("UTF-16", "UTF-8", inbuf, inlen, outbuf, outlen); } // - - - - - - - 以上是在Linux上实现的字符集转换函数
2、