1. 程式人生 > >VS2013在Unicode字符集下讀寫ANSI編碼檔案

VS2013在Unicode字符集下讀寫ANSI編碼檔案

讀取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();