一个Default编码的.txt文件 如何转成UTF-8类型编码的

时间:2023-01-06 21:51:06
是这样的。一个.txt文件 需要在程序里直接转化成UTF-8编码的
功能类似EditPlus的 ..File\save as..\Converter功能
恳求各位高手VC如何实现 

5 个解决方案

#1


MultiByteToWideChar

#2


up

#3


上次写的Ansi文本文件 to UTF8转换的代码


char* szAnsiBuf,*szUTF8Buf;
WCHAR* szUnicodeBuf;
int nAnsiFileLength,nWCHAR,nUTF8;
char* u8flag="\xef\xbb\xbf";
CFile file,tarfile;
if(file.Open("C:\\1.txt",CFile::modeRead))
{
nAnsiFileLength=file.GetLength();
szAnsiBuf=new char[nAnsiFileLength+1];
szUnicodeBuf=new WCHAR[nAnsiFileLength+1];
szUTF8Buf=new char[nAnsiFileLength*2+1]; 

file.Read(szAnsiBuf,nAnsiFileLength);
nWCHAR=MultiByteToWideChar(CP_ACP,0,szAnsiBuf,nAnsiFileLength,szUnicodeBuf,nAnsiFileLength);
nUTF8=WideCharToMultiByte(CP_UTF8,0,szUnicodeBuf,nWCHAR,szUTF8Buf,nAnsiFileLength*2,NULL,NULL);
tarfile.Open("C:\\2.txt",CFile::modeCreate|CFile::modeWrite);
tarfile.Write(u8flag,3);
tarfile.Write(szUTF8Buf,nUTF8);
tarfile.Close();
delete[] szAnsiBuf;
delete[] szUnicodeBuf;
delete[] szUTF8Buf;
file.Close();
}


#4


收到 谢谢各位 greatws的代码一点也没错

#5


学习了

#1


MultiByteToWideChar

#2


up

#3


上次写的Ansi文本文件 to UTF8转换的代码


char* szAnsiBuf,*szUTF8Buf;
WCHAR* szUnicodeBuf;
int nAnsiFileLength,nWCHAR,nUTF8;
char* u8flag="\xef\xbb\xbf";
CFile file,tarfile;
if(file.Open("C:\\1.txt",CFile::modeRead))
{
nAnsiFileLength=file.GetLength();
szAnsiBuf=new char[nAnsiFileLength+1];
szUnicodeBuf=new WCHAR[nAnsiFileLength+1];
szUTF8Buf=new char[nAnsiFileLength*2+1]; 

file.Read(szAnsiBuf,nAnsiFileLength);
nWCHAR=MultiByteToWideChar(CP_ACP,0,szAnsiBuf,nAnsiFileLength,szUnicodeBuf,nAnsiFileLength);
nUTF8=WideCharToMultiByte(CP_UTF8,0,szUnicodeBuf,nWCHAR,szUTF8Buf,nAnsiFileLength*2,NULL,NULL);
tarfile.Open("C:\\2.txt",CFile::modeCreate|CFile::modeWrite);
tarfile.Write(u8flag,3);
tarfile.Write(szUTF8Buf,nUTF8);
tarfile.Close();
delete[] szAnsiBuf;
delete[] szUnicodeBuf;
delete[] szUTF8Buf;
file.Close();
}


#4


收到 谢谢各位 greatws的代码一点也没错

#5


学习了