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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5026555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:12:40  来源:igfitidea点击:

c++ how to write/read ofstream in unicode / utf8

c++stringunicodeutf-8character-encoding

提问by user63898

I have UTF-8 text file , that I'm reading using simple :

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

ifstream in("test.txt");

Now I'd like to create a new file that will be UTF-8 encoding or Unicode. How can I do this with ofstreamor other? This creates ansi Encoding.

现在我想创建一个新文件,它将是 UTF-8 编码或 Unicode。我怎样才能做到这一点ofstream或其他?这将创建 ansi 编码。

ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);

回答by Yarkov Anton

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

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

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.hto 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 UTFand write your content there:

    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...
    
  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();
    
  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...