欢迎来到代码驿站!

Linux

当前位置:首页 > 服务器 > Linux

Linux下实现UTF-8和GB2312互相转换的方法

时间:2020-12-09 20:34:17|栏目:Linux|点击:

实例如下:

#include<iconv.h> #include <stdio.h>

#include<iconv.h>
using namespace std;
int utf8togb2312(const char *sourcebuf,size_t sourcelen,char *destbuf,size_t destlen) { 

iconv_t cd; 

if( (cd = iconv_open("gb2312","utf-8")) ==0 )  

  return -1; 

memset(destbuf,0,destlen); 

const char **source = &sourcebuf; 

char **dest = &destbuf;
if(-1 == iconv(cd,source,&sourcelen,dest,&destlen))  

  return -1; 

iconv_close(cd); 

return 0; 

}
int gb2312toutf8(const char *sourcebuf,size_t sourcelen,char *destbuf,size_t destlen) { 

iconv_t cd; if( (cd = iconv_open("utf-8","gb2312")) ==0 )  

return -1; memset(destbuf,0,destlen); 

const char **source = &sourcebuf; 

char **dest = &destbuf;
 if(-1 == iconv(cd,source,&sourcelen,dest,&destlen))  

return -1; 

iconv_close(cd); 

return 0; 

}
int main() { 

char line[80]; 

char dest_gb2312[200]; 

char dest_utf8[200]; 

int ret ; 

FILE *fp = fopen("love.txt","r"); 

if(fp == NULL) 

{  

printf("oh my dear,open fail...\n");  

return 1; 

}

 memset(line,0,80); 

if( NULL == fgets(line,80,fp)) 

{  

printf("oh fgets fail...\n");  

return 2; 

}

printf( "----- :%s\n",line );

ret = gb2312toutf8(line,strlen(line),dest_gb2312,200); 

// ret = gb2312toutf8(dest_gb2312,strlen(dest_gb2312),dest_utf8,80); 

printf( "ret=%d\n\n\n",ret); 

printf( "gb2312:%s\n",line ); 

printf( " utf-8:%s\n\n\n\n\n\n", dest_gb2312 );

 ret = utf8togb2312(dest_gb2312,strlen(dest_gb2312),dest_utf8,200); 

printf( "ret=%d\n\n\n ",ret); 

printf( " utf-8:%s\n ",dest_gb2312); 

printf( "gb2312:%s\n ",dest_utf8);

 return 0;

}

上一篇:Linux 下sftp配置之密钥方式登录详解

栏    目:Linux

下一篇:Ubuntu 安装Eclipse 菜单无法使用解决办法

本文标题:Linux下实现UTF-8和GB2312互相转换的方法

本文地址:http://www.codeinn.net/misctech/30943.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有