- //写UTF-8文件
- class WriteUTF8File
- {
- public:
- WriteUTF8File(const char* strFile)
- :m_pFile(NULL)
- {
- if (!Init(strFile))
- m_pFile = NULL;
- }
- ~WriteUTF8File()
- {
- if (m_pFile != NULL)
- fclose(m_pFile);
- }
- BOOL Good(){return m_pFile != NULL; }
- void WriteEx(const char* szBuf)
- {
- if (!Write(szBuf))
- throw std::exception("写文件失效或者打开文件失败\n");
- }
- BOOL Write(const char* szBuf)
- {
- if (m_pFile == NULL)
- return FALSE;
- std::string lstrUTF8;
- std::string lstrAnsi(szBuf);
- std::wstring lstrUnicode;
- int nLen = 0;
- nLen = MultiByteToWideChar( CP_ACP, 0, lstrAnsi.c_str(), -1, NULL, 0);
- if (nLen == 0 && GetLastError() != NO_ERROR)
- return FALSE;
- lstrUnicode.resize(nLen);
- int nRet = ::MultiByteToWideChar( CP_ACP, 0, lstrAnsi.c_str(), -1, (LPWSTR)lstrUnicode.c_str(), nLen);
- if (nRet == 0 && GetLastError() != NO_ERROR)
- return FALSE;
- lstrUnicode.resize(nLen - 1);
- nLen = WideCharToMultiByte( CP_UTF8, 0, lstrUnicode.c_str(), -1, 0, 0, 0, 0);
- if (nLen == 0 && GetLastError() != NO_ERROR)
- return FALSE;
- lstrUTF8.resize(nLen);
- nRet = ::WideCharToMultiByte(CP_UTF8, 0, lstrUnicode.c_str(), -1, (char*)lstrUTF8.c_str(), nLen, 0, 0);
- if (nRet == 0 && GetLastError() != NO_ERROR)
- return FALSE;
- lstrUTF8.resize(nLen - 1);
- int nX = 0;
- nX = fwrite(lstrUTF8.c_str(), 1, lstrUTF8.length(), m_pFile);
- if (nRet == -1)
- {
- nX = NULL;
- return FALSE;
- }
- return TRUE;
- }
- protected:
- BOOL Init(const char* strFile)
- {
- m_pFile = fopen(strFile, "w+b");
- if (m_pFile == NULL)
- return FALSE;
- char line[3]; // UTF-8 file header
- line[0] = 0xef;
- line[1] = 0xbb;
- line[2] = 0xbf;
- int nRet = fwrite(line, sizeof(char), 3, m_pFile);
- if (nRet == 3)
- return TRUE;
- return FALSE;
- }
- FILE* m_pFile;
- };