转换之前需要做一些工作,首先是要将libxml2的源码包和libiconv的源码包解压到电脑上,没有的同学可以到网站上下载,刚刚上传了上去。找不到的同学可以到官网上下载最新的源码包
http://www.gnu.org/software/libiconv/
具体安装步骤:
1、解压:$tar zxvf libxml2-2.6.20.tar.gz
2、进入解压后的安装目录:$cd libxml2-2.6.20
3、安装三部曲:1)$./configure
2)$make
3)$make install
libiconv源码包的步骤同上。
下面进行代码的转换
首先我们要建立一个动态库,方便我们的转换
先进入vi编译器
vi iconv.c
#include<iconv.h>
#include <stdio.h>
#include<iconv.h>
#include <stdio.h>
int utf8togb18030(const char *sourcebuf,size_t sourcelen,char *destbuf,size_t destlen)
{
iconv_t cd;
if( (cd = iconv_open("gb18030","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 gb18030toutf8(const char *sourcebuf,size_t sourcelen,char *destbuf,size_t destlen)
{
iconv_t cd;
if( (cd = iconv_open("utf-8","gb18030")) ==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;
}
保存退出
root@:~/czy/test/test# gcc -shared -fpic -o libmy.so iconv.c
root@:~/czy/test/test这一行是我测试的地方
真正生成动态库的命令是gcc -shared -fpic -o libmy.so iconv.c
-fpic 使输出的对象模块是按照可重定位地址方式生成的。
-shared指定把对应的源文件生成对应的动态链接库文件。
动态库建成,此时就要进行我们的代码转换了。
vi main.c
#include <stdio.h>
#include <assert.h>//设定插入点
#include <ctype.h>//字符处理
#include <errno.h>//定义错误码
#include <float.h>//浮点数处理
#include <limits.h>//定义各种数据类型最值常量
#include <locale.h>//定义本地化函数
#include <math.h>//定义数学函数
#include <stdio.h>//定义输入/输出函数
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <string.h>//字符串处理
#include <time.h>//定义关于时间的函数
#include <wchar.h>//宽字符处理及输入/输出
#include <wctype.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main(int argc, char* argv[])
{
char line[1024*512];
char dest_gb18030[1024*512];
char dest_utf8[1024*512];
int ret ;
FILE *fp = fopen("/root/czy/test/test/123_GB18030.xml","r"); //fopen函数指定打开自己要转换的文件
if(fp == NULL)
{
printf("oh my dear,open fail...\n");
return 1;
}
memset(line,0,sizeof(line));
if( NULL == fread(line,1,sizeof(line)-1,fp))
{
printf("oh fread fail...\n");
return 2;
}
printf( "----- :%s\n",line );
ret = gb18030toutf8(line,strlen(line),dest_gb18030,1024*512);
printf( "ret=%d\n\n\n",ret);
printf( "gb18030:%s\n",line );
printf( " utf-8:%s\n\n\n\n\n\n", dest_gb18030 );
ret = utf8togb18030(dest_gb18030,strlen(dest_gb18030),dest_utf8,1024*512);
printf( "ret=%d\n\n\n ",ret);
printf( " utf-8:%s\n ",dest_gb18030);
printf( "gb18030:%s\n ",dest_utf8);
}
这里我将常见的头文件全部列出,方便大家学习。
root@:~/czy/test/test# gcc -I/root/czy/test/libxml/libxml2-2.9.0/include -o t main.c -L./ -lmy -lxml2 -L/root/czy/test/libxml/libiconv-1.14/lib/.libs -liconv
-I/root/czy/test/libxml/libxml2-2.9.0/include这一行是我解压的libxml源码位置,-I表示在include下搜索目录,-L表示在库中搜索目录。
此时我们回车后没有错误,但当我们./t 时就提示了错误
这是因为我们没有设置好环境变量
root@:~/czy/test/test# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./
设置一下当前的环境变量
在./t 我们就回得到我们想要的结果了