在利用tinyXML和miniXML的时候,需要将文本文件从ANSI编码格式转为UTF-8格式,否则不能使用。
转换的前提是在VS.net 中,将项目-属性-配置属性-常规-字符集 改为多字节字符集。由于(默认是unicode),改动过程可能需要从MS下载多字节字符集的相关库。
转换代码如下:
CStdioFile file;
if (!file.Open(_T("output.txt"), CFile::modeRead)) {
MessageBox(_T("open output.txt failed!"));
}
//逐行读取ANSI字符串
CString strText;
CString strLine;
while (file.ReadString(strLine))
{
strText += strLine;
}
file.Close(); //关闭文件
MessageBox(strText);
// 1. 转成宽字节的ANSI
int nwLen = ::MultiByteToWideChar(CP_ACP, 0, strText, -1, NULL, 0);
wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
::memset(pwBuf, 0, nwLen * 2 + 2); //每个宽字符(unicode)都是双字节
int len = ::MultiByteToWideChar(CP_ACP, 0, strText, strText.GetLength(), pwBuf, nwLen);
// 2. 宽字节的ANSI --> 多字节的UTF8
int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char * pBuf = new char[nLen + 1];
::memset(pBuf, 0, nLen + 1);
::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
/////////////////////////////////////////////////
std::ofstream ofs("data.txt", std::ofstream::out);
ofs << pBuf;