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

标签 c++ string unicode utf-8 character-encoding

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

ifstream in("test.txt");

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

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

最佳答案

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

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

  1. Read the article about UTF converter for streams
  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...
    

关于c++ 如何在 unicode/utf8 中写入/读取 ofstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026555/

相关文章:

c - 如何使用 C 从 UTF-16 文件映射 Unicode 代码点

python - 无法发送包含西里尔字母的电子邮件

c++ - 尝试在 Visual Studio 2013 中使用 sqlite3_open 进行编译时出错

c++ - 在 C++ 中使用 OpenMP 并行化递归函数

c++ - 程序可以使用管道来回通信吗?

java - 在每个元音前添加文本

java - 所有的转义字符是什么?

c++ - 复制构造函数和=运算符有什么区别

java - 这里会创建多少个 String 对象?

Java - é 变成 É - 如何修复