MFC Unicode字符集下 CFile CString UTF-8文件 ANSI 文件
1
读取ANSI编码的文件时,现将文件存储在char* 指向的内存内,而后使用转换将char转换为wchar_t。wchar_t*可以使用CString的Format函数。
CFile file(_T("test.txt"), CFile::modeRead);//读ANSI编码的文件
int filelen = file.GetLength();
char *p = new char[filelen + 1];
file.Read(p, filelen);
p[filelen] = '\0';
USES_CONVERSION;//转化为wchar_t* 可以使用CString的Format函数。
wchar_t* wp = new wchar_t[filelen + 1];
wp = A2T(p);
str.Format(_T("%s"), wp)
file.close();
写ANSI文件时,将Unicode编码的CString转化为ANSI编码的CStringA,要获取ANSI格式的字符只需使用GetBuffer即可。也可使用WideCharToMultiByte转换。
CStringA str_ANSI(str.GetBuffer(0));
CFile file_ANSI(_T("test_ANSI.txt"), CFile::modeCreate | CFile::modeWrite);//写ANSI编码的文件
file_ANSI.Write(str_ANSI.GetBuffer(), str_ANSI.GetLength());
//CFile file_ANSI(_T("test_ANSI.txt"), CFile::modeCreate | CFile::modeWrite);
//file_ANSI.Write(p, filelen);
file_ANSI.close();
2
MultiByteToWideChar
MultiByteToWideChar(CP_ACP, 0, postJsonAlarmCstr2T2A, -1, pszUnicode, dwCount);
WideCharToMultiByte
WideCharToMultiByte(CP_UTF8, 0, pszUnicode, -1, pszUTF8 + sizeof(arUTF8Header), dwCount - sizeof(arUTF8Header), NULL, NULL);
MFC中ANSI与Unicode文件读写转换
这篇博客介绍了在MFC环境下,如何在Unicode字符集中读取和写入ANSI编码的文件。首先展示了读取ANSI文件的过程,通过CFile读取内容到char*,然后使用A2T转换为wchar_t*,再利用CString的Format函数处理。接着,文章说明了如何将Unicode的CString转换为ANSI编码并写入文件,利用GetBuffer获取ANSI格式的字符,最后写入CFile。此外,还提到了MultiByteToWideChar和WideCharToMultiByte两个转换函数在处理编码转换中的作用。
3207

被折叠的 条评论
为什么被折叠?



