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

2022-01-07 00:00:00 unicode string utf-8 character-encoding c++

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

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

ifstream in("test.txt");

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

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

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

推荐答案

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

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

但是如果你想使用具有旧标准的多平台代码,你可以使用这种方法来编写流:

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

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

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

  • 然后以 UTF 格式打开文件并在其中写入您的内容:

  • 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<false>);
    fs.imbue(utf8_locale); 
    
    fs << .. // Write anything you want...
    

  • 相关文章