Writing utf16 to file in binary mode

前端 未结 6 1140
逝去的感伤
逝去的感伤 2020-11-27 04:44

I\'m trying to write a wstring to file with ofstream in binary mode, but I think I\'m doing something wrong. This is what I\'ve tried:

ofstream outFile(\"tes         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 05:35

    It is easy if you use the C++11 standard (because there are a lot of additional includes like "utf8" which solves this problems forever).

    But if you want to use multi-platform code with older standards, you can use this method to write with streams:

    1. Read the article about UTF converter for streams
    2. Add stxutif.h to your project from sources above
    3. Open the file in ANSI mode and add the BOM to the start of a file, like this:

      std::ofstream fs;
      fs.open(filepath, std::ios::out|std::ios::binary);
      
      unsigned char smarker[3];
      smarker[0] = 0xEF;
      smarker[1] = 0xBB;
      smarker[2] = 0xBF;
      
      fs << smarker;
      fs.close();
      
    4. Then open the file as UTF and write your content there:

      std::wofstream fs;
      fs.open(filepath, std::ios::out|std::ios::app);
      
      std::locale utf8_locale(std::locale(), new utf8cvt);
      fs.imbue(utf8_locale); 
      
      fs << .. // Write anything you want...
      

提交回复
热议问题