utf 8ファイル操作



  
  
  
  
  1. // UTF-8  
  2. class WriteUTF8File  
  3. {  
  4. public:  
  5.     WriteUTF8File(const char* strFile)  
  6.         :m_pFile(NULL)  
  7.     {  
  8.         if (!Init(strFile))  
  9.             m_pFile = NULL;  
  10.     }  
  11.     ~WriteUTF8File()  
  12.     {  
  13.         if (m_pFile != NULL)  
  14.             fclose(m_pFile);  
  15.     }  
  16.     BOOL Good(){return m_pFile != NULL; }  
  17.     void WriteEx(const char* szBuf)  
  18.     {  
  19.         if (!Write(szBuf))  
  20.             throw std::exception("
    ");  
  21.     }  
  22.     BOOL Write(const char* szBuf)  
  23.     {  
  24.         if (m_pFile == NULL)  
  25.             return FALSE;  
  26.         std::string lstrUTF8;  
  27.         std::string lstrAnsi(szBuf);  
  28.         std::wstring lstrUnicode;  
  29.         int nLen = 0;  
  30.         nLen = MultiByteToWideChar( CP_ACP, 0, lstrAnsi.c_str(), -1, NULL, 0);  
  31.         if (nLen == 0 && GetLastError() != NO_ERROR)  
  32.             return FALSE;  
  33.         lstrUnicode.resize(nLen);  
  34.         int nRet = ::MultiByteToWideChar( CP_ACP, 0, lstrAnsi.c_str(), -1, (LPWSTR)lstrUnicode.c_str(), nLen);  
  35.         if (nRet == 0 && GetLastError() != NO_ERROR)  
  36.             return FALSE;  
  37.         lstrUnicode.resize(nLen - 1);  
  38.           
  39.         nLen = WideCharToMultiByte( CP_UTF8, 0, lstrUnicode.c_str(), -1, 0, 0, 0, 0);  
  40.         if (nLen == 0 && GetLastError() != NO_ERROR)  
  41.             return FALSE;  
  42.         lstrUTF8.resize(nLen);  
  43.         nRet = ::WideCharToMultiByte(CP_UTF8, 0, lstrUnicode.c_str(), -1, (char*)lstrUTF8.c_str(), nLen, 0, 0);  
  44.         if (nRet == 0 && GetLastError() != NO_ERROR)  
  45.             return FALSE;  
  46.         lstrUTF8.resize(nLen - 1);  
  47.         int nX = 0;  
  48.         nX = fwrite(lstrUTF8.c_str(), 1, lstrUTF8.length(), m_pFile);  
  49.         if (nRet == -1)  
  50.         {  
  51.             nX = NULL;  
  52.             return FALSE;  
  53.         }  
  54.         return TRUE;  
  55.     }  
  56. protected:  
  57.     BOOL Init(const char* strFile)  
  58.     {  
  59.         m_pFile = fopen(strFile, "w+b");  
  60.         if (m_pFile == NULL)  
  61.             return FALSE;  
  62.         char line[3]; // UTF-8 file header  
  63.         line[0] = 0xef;  
  64.         line[1] = 0xbb;  
  65.         line[2] = 0xbf;  
  66.         int nRet = fwrite(line, sizeof(char), 3, m_pFile);  
  67.         if (nRet == 3)  
  68.             return TRUE;  
  69.         return FALSE;  
  70.     }  
  71.     FILE* m_pFile;  
  72. };