1.utf8保存文件绝对是没有问题,可以有bom和无bom格式,并且支持多个多国家语言。
2.ansi保存中文会出现乱码情况。
#if USE_UTF8
FILE* f = _wfopen(_T("t.log"), _T("w+, ccs=UTF-8"));
if (f) {
wchar_t wbuffer[30];
wmemset(wbuffer, 0, _countof(wbuffer));
wcscpy(wbuffer, _T("中国"));
fwrite(wbuffer, sizeof(wchar_t)*wcslen(wbuffer), 1, f);
wcscpy(wbuffer, _T("\r\n"));
fwrite(wbuffer, sizeof(wchar_t)*wcslen(wbuffer), 1, f);
wcscpy(wbuffer, _T("你好"));
fwrite(wbuffer, sizeof(wchar_t)*wcslen(wbuffer), 1, f);
fclose(f);
}
#else
FILE* f = fopen("t.log", "w+, ccs=ANSI");
if (f) {
char cbuffer[30];
memset(cbuffer, 0, sizeof(cbuffer));
strcpy(cbuffer, "中国");
fwrite(cbuffer, sizeof(char)*strlen(cbuffer), 1, f);
strcpy(cbuffer, "\r\n");
fwrite(cbuffer, sizeof(char)*strlen(cbuffer), 1, f);
strcpy(cbuffer, "你好");
fwrite(cbuffer, sizeof(char)*strlen(cbuffer), 1, f);
fclose(f);
}
#endif
class StringHelper{
public :
static std::wstring Char2Wchar(std::string stdChar);
static std::string Wchar2Char(std::wstring stdWchar);
static std::string CString2String(ATL::CString str);
};
std::string StringHelper::Wchar2Char(std::wstring stdWchar)
{
std::string RetString;
int mb_size = ::WideCharToMultiByte(CP_ACP, 0, stdWchar.c_str(), -1, NULL, 0, NULL, NULL);
if(mb_size) {
char* temp = new char[mb_size];
mb_size = ::WideCharToMultiByte(CP_ACP, 0, stdWchar.c_str(), -1, temp, mb_size, NULL, NULL);
RetString = temp;
delete temp;
temp = NULL;
}
return RetString;
}
std::wstring StringHelper::Char2Wchar(std::string stdChar)
{
std::wstring RetString;
int wd_size = ::MultiByteToWideChar(CP_UTF8, 0, stdChar.c_str(), -1, NULL, 0);
if (wd_size) {
wchar_t* temp = new wchar_t[wd_size];
::MultiByteToWideChar(CP_UTF8, 0, stdChar.c_str(), -1, temp, wd_size);
RetString = temp;
delete temp;
temp = NULL;
}
return RetString;
}
std::string StringHelper::CString2String(ATL::CString str)
{
std::string RetString;
RetString = Wchar2Char((LPCTSTR)str);
return RetString;
}