案例一:C++里流文件读取字符串时产生的各种不确定编码问题
wstring strFilePath;
strFilePath = strResourcePath + _T("lang\\") + FindFileData.cFileName;
ifstream OpenFile(strFilePath);
if(OpenFile.fail()) continue;
在流文件读取的时候,编码转换很容易出错,解决方法就是不要使用这种办法读取
案例二:编码具体转换
wstring CSettingCenter::UTF8ToGB(const char * strText)
{
string result;
WCHAR *strSrc;
LPSTR szRes;
//获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, 0, strText, -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, strText, -1, strSrc, i);
//获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return (CA2W)result.c_str();
}
此方法转换过程中比较繁杂
案例三 :最好的解决办法CA2WEX<>(sep, CP_UTF8)转
strFilePath = CPaintManagerUI::GetResourcePath() + _T("lang\\") + FindFileData.cFileName;
HANDLE hFile = ::CreateFileW(strFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwSize = ::GetFileSize(hFile, NULL);
if (!dwSize)
{
CloseHandle(hFile);
break;
}
pLanguageData = new CHAR[dwSize + 1];
DWORD dwRead = 0;
::ReadFile(hFile, pLanguageData, dwSize, &dwRead, NULL);
dwLanguageDataSize = dwRead;
CloseHandle(hFile);
vector<wstring> vctText;
vctTemp.clear();
if (!pLanguageData) return;
char* next_start = pLanguageData;
char* start = next_start;
char* end = strchr(start, '\n');
if (end)
{
*end = 0;
}
char* sep = strchr(start, '=');
if (!sep)
{
continue;
}
*sep = 0;
sep++;
wstring value = CA2WEX<>(sep, CP_UTF8);
案例四 用C语言发FILE fopen打开问文件,或者MFC的CFile方法打开
深圳C++交流群876027056
问题咨询微信18926447914,可拉入微信深圳程序员交流群,有大厂直连HR招聘内推,以及各大神