Ansi、Unicode、UTF8等編碼字串之間的轉換和寫入文字檔案(學習中……)
阿新 • • 發佈:2019-02-09
{
// ansi to unicode
char* szAnsi ="abcd1234你我他";
//預轉換,得到所需空間的大小
int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), NULL, 0);
//分配空間要給'/0'留個空間,MultiByteToWideChar不會給'/0'空間
wchar_t* wszString =new wchar_t[wcsLen +1];
//轉換
::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), wszString, wcsLen);
//最後加上'/0'
wszString[wcsLen] ='/0';
//unicode版的MessageBox API
::MessageBoxW(GetSafeHwnd(), wszString, wszString, MB_OK);
//接下來寫入文字
//寫文字檔案,頭2個位元組0xfeff,低位0xff寫在前
CFile cFile;
cFile.Open(_T("1.txt"), CFile::modeWrite | CFile::modeCreate);
//檔案開頭
cFile.SeekToBegin();
cFile.Write("/xff/xfe ", 2);
//寫入內容
cFile.Write(wszString, wcsLen *sizeof(wchar_t));
cFile.Flush();
cFile.Close();
delete[] wszString;
wszString =NULL;
//方法2
//設定當前地域資訊,不設定的話,使用這種方法,中文不會正確顯示
//需要#include<locale.h>
setlocale(LC_CTYPE, "chs");
wchar_t wcsStr[100];
//注意下面是大寫S,在unicode中,代表後面是ansi字串
//swprintf是sprintf的unicode版本
//格式的前面要加大寫L,代表是unicode
swprintf(wcsStr, L"%S", szAnsi);
::MessageBoxW(GetSafeHwnd(), wcsStr, wcsStr, MB_OK);
}
// ansi to unicode
char* szAnsi ="abcd1234你我他";
//預轉換,得到所需空間的大小
int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), NULL, 0);
//分配空間要給'/0'留個空間,MultiByteToWideChar不會給'/0'空間
wchar_t* wszString =new wchar_t[wcsLen +1];
//轉換
::MultiByteToWideChar(CP_ACP, NULL, szAnsi, strlen(szAnsi), wszString, wcsLen);
wszString[wcsLen] ='/0';
//unicode版的MessageBox API
::MessageBoxW(GetSafeHwnd(), wszString, wszString, MB_OK);
//接下來寫入文字
//寫文字檔案,頭2個位元組0xfeff,低位0xff寫在前
CFile cFile;
cFile.Open(_T("1.txt"), CFile::modeWrite | CFile::modeCreate);
//檔案開頭
cFile.SeekToBegin();
cFile.Write("/xff/xfe
//寫入內容
cFile.Write(wszString, wcsLen *sizeof(wchar_t));
cFile.Flush();
cFile.Close();
delete[] wszString;
wszString =NULL;
//方法2
//設定當前地域資訊,不設定的話,使用這種方法,中文不會正確顯示
//需要#include<locale.h>
setlocale(LC_CTYPE, "chs");
wchar_t wcsStr[100];
//注意下面是大寫S,在unicode中,代表後面是ansi字串
//格式的前面要加大寫L,代表是unicode
swprintf(wcsStr, L"%S", szAnsi);
::MessageBoxW(GetSafeHwnd(), wcsStr, wcsStr, MB_OK);
}