您的位置:首页 > 其它

GB2312转UTF8示例程序

2013-04-28 14:13 239 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: