GB2312转UTF8示例程序

本文介绍了一个用于将GB2312编码的字符串转换为UTF-8编码的实用函数,并展示了如何从XML文件中读取内容并进行编码转换的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <Windows.h>
#include <stdio.h>
#include <string>

 

bool GB2312ToUTF8(const char *pGb2312,std::string &strUtf8)
{
   //GB2312 to unicode
   int nUniCodeLen = MultiByteToWideChar(CP_ACP,0,pGb2312,-1,NULL,0);
   wchar_t *pcUnicode = new wchar_t[nUniCodeLen + 1];
   memset(pcUnicode,0,nUniCodeLen * 2 +2);

   MultiByteToWideChar(CP_ACP,0,pGb2312,-1,pcUnicode,nUniCodeLen);

   //unicode to utf8
 int nUtf8Len = WideCharToMultiByte(CP_UTF8,0,pcUnicode,-1,NULL,0,NULL,NULL);
 char *pcUtf8 = new char[nUtf8Len + 1];
 memset(pcUtf8,0,nUtf8Len +1 );
 WideCharToMultiByte(CP_UTF8,0,pcUnicode,-1,pcUtf8,nUtf8Len,NULL,NULL);
 strUtf8 = pcUtf8;
 delete []pcUtf8;
 delete []pcUnicode;
 return true;
}

std::string getContentsFromXmlFile(std::string &fileName)
{
 FILE *fp = NULL;
 if((fp = fopen(fileName.c_str(),"rb")) == NULL)
 {
  printf("file: %s open error ! ",fileName.c_str());
  std::string sTmp;
  return sTmp;
 }
 fseek(fp,0,SEEK_SET);
 fseek(fp,0,SEEK_END);
 int fileSize = ftell(fp) + 1;
 if(!(fileSize - 1 > 5))
 {
  std::string temp("");
  fclose(fp);
  return temp;
 }
 char *pchBuffer = new char[fileSize];
 fseek(fp,0,SEEK_SET);
 memset(pchBuffer,0,fileSize);
 fread(pchBuffer,fileSize,1,fp);
 pchBuffer[fileSize - 1] = '\0';
 std::string fileContent(pchBuffer);

 if(pchBuffer != NULL)
 {
  delete []pchBuffer;
  pchBuffer = NULL;
 }
 fclose(fp);
 return fileContent;
}

std::string getContentsFromXmlFile(const char *filename)
{
 std::string strFileName(filename);
 return getContentsFromXmlFile(strFileName);
}


int main(int argc,char **argv)
{
 std::string strXmlContent = getContentsFromXmlFile("fileName.xml");
 std::string strResult;
 GB2312ToUTF8(strXmlContent.c_str(),strResult);
 FILE *fp = fopen("result.xml","ab");
 fwrite(strResult.c_str(),strResult.length(),1,fp);
 fclose(fp);

 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值