将字符的编码转换为另一种编码

大耗子 2020年08月20日 45次浏览

将字符的编码转换为另一种编码

int code_convert(char *from_charset,char *to_charset,char *inbuf,size_t  inlen,char *outbuf,size_t  outlen)  
{  
    iconv_t cd;  
    //int rc;  
    char **pin = &inbuf;  
    char **pout = &outbuf;  

	dbg_filesync_msg(FILESYNC_DEBUG_DEBUG,"+++++peng from:%s  to:%s ++++\n", from_charset, to_charset);	
    cd = iconv_open(to_charset, from_charset);  
    if (cd == ( iconv_t)-1) { 
		perror("iconv_open");
		printf("+++++peng iconv_open error:%s++++\n", strerror(errno));	
        return -1;
    }
    memset(outbuf,0,outlen);  
    if (iconv(cd, pin, &inlen, pout, &outlen) == -1)  {
		perror("iconv");
		iconv_close(cd); 
		printf("+++++peng iconv error:%s++++\n", strerror(errno));	
        return -1;  
    }
    iconv_close(cd);  
    return 0;  
} 

转换成UTF-8编码

int file_match_code(char *in, char *out, int outlen) 
{
	char *charset = NULL;
	int ret = 0;
	int i;
	char *character_gather_chinese[5] = {"utf-8", "gb2312", "gbk", "big5", "gb18030"};

	if (in==NULL||out==NULL)
		return -1;

	for (i = 0; i < 5; i++) {
		memset(out, 0, outlen);
		ret = code_convert(character_gather_chinese[i], "utf-8", in, strlen(in), out, outlen);
		if (ret < 0) {
			printf("[file_match_code]code convert failed %s\n", character_gather_chinese[i]);
			continue;
		}else
			break;
	}
	if (ret < 0)
		strcpy(out, in);
	printf("[file_match_code]changeafetr buf:%s\n", out);
	return 0;

}

demo

#include <stdio.h>
#inlcude <iconv.h>
void main()
{
	char buf[1024]={0};
	file_match_code("中文",buf,1024);
	printf("%s\n",buf);
}