TA的每日心情 | 奋斗 2021-11-19 13:15 |
---|
签到天数: 20 天 连续签到: 1 天 [LV.4]偶尔看看III
|
研究了一段时间的iconv.h,终于在查看资料和实践下搞定了iconv这个函数,实现了对包含错误编码的字符串的转码。常见的情况就是,某些字符不属于GBK字符集,而将这个字符串由GBK转到UTF-8的时候就会出错。- int
- convert(const char *from, /*要转换的字符集*/
- const char *to, /*要转换到的字符集*/
- char* save, /*输出字符串*/
- int savelen, /*输出字符串缓存长度*/
- char *src, /*源字符串*/
- int srclen) /*源字符串长度*/
- {
- iconv_t cd;
- char *inbuf = src;
- char *outbuf = save;
- size_t outbufsize = savelen;
- int status = 0;
- size_t savesize = 0;
- size_t inbufsize = srclen;
- char* inptr = inbuf;
- size_t insize = inbufsize;
- char* outptr = outbuf;
- size_t outsize = outbufsize;
- cd = iconv_open(to, from);
- iconv(cd,NULL,NULL,NULL,NULL);
- if (inbufsize == 0) {
- status = -1;
- goto done;
- }
- while (insize > 0) {
- size_t res = iconv(cd,&inptr,&insize,&outptr,&outsize);
- if (res == (size_t)(-1)) {
- if (errno == EILSEQ) {
- inptr ++;
- status = -3;
- } else if (errno == EINVAL) {
- break;
- } else if (errno == E2BIG) {
- status = -5;
- goto done;
- } else {
- status = -6;
- goto done;
- }
- }
- }
- if (outptr != outbuf) {
- int outsize = outptr - outbuf;
- strncpy(save+savesize, outbuf, outsize);
- }
- status = strlen(save);
- done:
- iconv_close(cd);
- return status;
- }
复制代码 使用方法:- gchar *convert(gchar *from)
- {
- char *result = g_new(char, strlen(from) * 3 + 1);
- convert2("GBK", "UTF-8", result, strlen(from) * 3 + 1, from, strlen(from));
- if (result != NULL) return result;
- else return "";
- }
复制代码 |
|