c ++如何在unicode/utf8中编写/读取ofstream

use*_*898 12 c++ string unicode utf-8 character-encoding

我有UTF-8文本文件,我正在阅读使用简单:

ifstream in("test.txt");
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个UTF-8编码或Unicode的新文件.我怎么能用这个ofstream或其他?这会创建ansi编码.

ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
Run Code Online (Sandbox Code Playgroud)

小智 6

好的,关于便携式变体.如果你使用C++11标准就很容易(因为有很多额外的包含,比如"utf8",它永远解决了这个问题).

但是,如果要使用旧标准的多平台代码,可以使用此方法使用流写入:

  1. 阅读有关流的UTF转换器的文章
  2. stxutif.h从上面的来源添加到您的项目
  3. 以ANSI模式打开文件并将BOM添加到文件的开头,如下所示:

    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();
    
    Run Code Online (Sandbox Code Playgroud)
  4. 然后打开文件UTF并在那里写下您的内容:

    std::wofstream fs;
    fs.open(filepath, std::ios::out|std::ios::app);
    
    std::locale utf8_locale(std::locale(), new utf8cvt<false>);
    fs.imbue(utf8_locale); 
    
    fs << .. // Write anything you want...
    
    Run Code Online (Sandbox Code Playgroud)

  • 不要为UTF-8编写BOM!"Unicode标准既不要求也不建议使用UTF-8的BOM,"http://en.wikipedia.org/wiki/Byte_order_mark (4认同)