1. 程式人生 > >C++ fstream 讀寫 unicode 檔案

C++ fstream 讀寫 unicode 檔案

所謂的unicode檔案,無非就是在檔案頭部插入了 0xFFFE的標誌。。。讀寫的時候對應的讀寫 就可以了。

  1. namespace fileStream  
  2. {  
  3.     bool readFile_Unicode( const string &file ,wstring &destWstring)  
  4.     {  
  5.         destWstring.clear();  
  6.         //setlocale(LC_ALL,"Chinese-simplified");//設定中文環境
  7.         locale &loc=locale::global(locale(locale(),""
    ,LC_CTYPE));  
  8.         std::ifstream filestream (file.c_str(), std::ios::in|std::ios::binary|std::ios::ate);  
  9.         filestream.seekg (0, std::ios::end);  
  10.         size_t size = (size_t)filestream.tellg();  
  11.         filestream.seekg(0,ios::beg);  
  12.         char* buffer = newchar[size + 1];  
  13.         memset(buffer,0,sizeof
    (char)*(size + 1));  
  14.         filestream.read (buffer, size);  
  15.         destWstring = (wchar_t*)buffer;  
  16.         destWstring.erase(size/2);//刪除末尾可能會出現的亂碼 /2 是為了unicode 之後 長度只有一半
  17.         filestream.close();  
  18.         delete[] buffer;  
  19.         //setlocale(LC_ALL,"C");//還原
  20.         locale::global(loc);   
  21.         return
     !destWstring.empty();  
  22.     }  
  23.     bool writeFile_Unicode( const string &file ,const wstring &writeWstring )  
  24.     {  
  25.         //setlocale(LC_ALL,"Chinese-simplified");//設定中文環境
  26.         locale &loc=locale::global(locale(locale(),"",LC_CTYPE));   
  27.         std::ofstream filestream(file.c_str(), std::ios::out | std::ios::binary | std::ios::ate);  
  28.         filestream.clear();  
  29.         staticconstBYTE unicodeHead[]={0xFF,0xFE}; //unicode檔案標頭檔案
  30.         filestream.write((char *)unicodeHead,2);  
  31.         filestream.seekp(std::ios::end);  
  32.         filestream.write((char *)writeWstring.c_str(),writeWstring.length() * 2);  
  33.         filestream.close();  
  34.         //setlocale(LC_ALL,"C");//還原
  35.         locale::global(loc);   
  36.         returntrue;  
  37.     }  
  38. }