/* CodeConvert.c -- code convert function * Designed by falcon, 2006-9-16 , Email: zhangjinw[at]gmail.com * */ #include <iconv.h> #include <string.h> #include <errno.h> #include "CodeConvert.h" #ifndef BUF_MAX_LEN #define BUF_MAX_LEN 1024 /*you must set the sizeofbuf_temp larger then BUF_MAX_LEN*/ #endif char *code_knowned[] = { /*define you own codes here*/ /*0*/ "ASCII", /*1*/ "gb2312", /*2*/ "utf8", /*3*/ "gbk" }; /*code from one to another*/ int code_convert(char *from_code, char *to_code, char *from, char *to) { static iconv_t cd; static char *tptr, *fptr; static size_t ileft, oleft, ret; tptr = fptr =NULL; if(from == NULL || to == NULL) return -1; cd = iconv_open((const char *)to_code, (const char *)from_code); if (cd == (iconv_t)-1) { return -1; } ileft = strlen(from); fptr = from; for (;;) { tptr = to; oleft = BUF_MAX_LEN; ret = iconv(cd, &fptr, &ileft, &tptr, &oleft); if (ret != (size_t)-1) { break; } if (errno == EINVAL) { (void) memmove(from, fptr, ileft); (void) iconv(cd, &fptr, &ileft, &tptr, &oleft); (void) iconv_close(cd); return 1; } else if (errno == E2BIG) { continue; } else if (errno == EILSEQ) { (void) iconv(cd, &fptr, &ileft, &tptr, &oleft); (void) iconv_close(cd); return 1; } else if (errno == EBADF) { return -1; } else { return -1; } } (void) iconv(cd, &fptr, &ileft, &tptr, &oleft); (void) iconv_close(cd); return 0; } /*convert any code to the code you want,return the source code num*/ int code_convert_to(char *to_code, char *from, char *to) { static int i, ret, code_knowned_num; code_knowned_num = sizeof(code_knowned) / sizeof(code_knowned[0]); for(i = 0; i < code_knowned_num; i++) { ret = code_convert( code_knowned[i], to_code, from, to); if (ret == 0) return i; else if (ret == 1) continue; else{ return -1; } } } /*convert any code to utf8*/ char * c2localencode(char *from, char *to) { static int ret; ret = code_convert_to(LOCAL_ENCODE, from, to); if (ret == -1) { return NULL; } else { return to; } } char * c2localencoders(char *from, char *to, int *source_code) { static int ret; ret = code_convert_to(LOCAL_ENCODE, from, to); if (ret == -1) { return NULL; } else { *source_code = ret; return to; } } |