iconv 关于c++的编码转换

kurorohisoka 2009-05-07 04:17:45
我是在fedora下写的,为什么我转换后输出总是空?代码如下:
#include <iostream>
#include <fstream>
#include <iconv.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
char i;
fstream fs;
fs.open("sina.html",fstream::in|fstream::binary);
string instr="";
while(!fs.eof())
{
fs>>i;
if(fs.eof())break;
instr+=i;
}
instr+='\n';
size_t length=instr.length();
char* inbuf=(char*)malloc(length+1);
for(int h=0;h<length;h++)
{
inbuf[h]=instr[h];
}
inbuf[length]='\0';
char* outbuf=new char[length*2];
char* outptr;
//outbuf=(char*)malloc(length*2);
outptr=outbuf;
memset(outbuf,'\0',length*2);
iconv_t cd;
cd=iconv_open("utf-8","GB2312");
if(cd==(iconv_t)-1)
{
cout<<"fail"<<endl;
}
size_t avail=length*2;
size_t nconv=iconv(cd,&inbuf,&length,&outbuf,&avail);
cout<<outbuf<<endl;
iconv_close(cd);
return 1;
}

谢谢大家了!
...全文
103 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
pathuang68 2009-05-07
  • 打赏
  • 举报
回复
顶一下
w0911h 2009-05-07
  • 打赏
  • 举报
回复
另外你读文件的时候用char可能有问题,改成unsined char试试
w0911h 2009-05-07
  • 打赏
  • 举报
回复
这是我程序中的一段转换代码,希望对你有帮助

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

cd = iconv_open(to_charset,from_charset);
if(cd==0) return -1;

memset(outbuf,0,outlen);

if(iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1;

iconv_close(cd);
return 0;
}

/*UNICODE码转为GB2312码*/
int u2g(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}

/*GB2312码转为UNICODE码*/
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}
hoomien 2009-05-07
  • 打赏
  • 举报
回复
帮顶
kurorohisoka 2009-05-07
  • 打赏
  • 举报
回复
sina.html是我把新浪的主页,查看源代码,然后复制保存到一个html的文件中。

64,680

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧