如何在C++中以Unicode/UTF-8格式编写/读取ofstream?

14

我有一个使用UTF-8编码的文本文件,我正在使用简单的方法来读取它:

ifstream in("test.txt");

我想创建一个新文件,使其采用UTF-8编码或Unicode。我该如何使用ofstream或其他方法实现?当前代码创建的是ANSI编码。

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

1
这篇文章可能会有所帮助:在C++中以可移植的方式使用UTF-8 - Rob
你是说utf8不是Unicode吗? - Jörgen Sigvardsson
请提供一个最小但完整的代码示例,以展示您所描述的行为。 - JB.
@Jörgen - Unicode可以以许多格式进行编码,其中UTF-8只是其中之一。例如,UTF-16编码的Unicode与UTF-8编码的Unicode一样都是Unicode,但尝试将其解析为UTF-8很可能会使您的解码器崩溃和烧毁。因此,最好明确要谈论哪种编码的Unicode字符表。 - user
2
Utf8 就像 utf16 和 utf32 一样是 Unicode。没有字符表。Unicode 是代码到字符的映射。UtfX 是以可移植的方式表示代码的方法。 - Jörgen Sigvardsson
1个回答

5

好的,关于便携式变量。如果您使用C++11标准(因为有许多附加包括"utf8"的内容,可以永久解决此问题),那么很容易。

但是如果您想要使用旧标准的多平台代码,您可以使用以下方法使用流进行编写:

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

UCS-2和UTF-16编码规范指定了Unicode字节顺序标记(BOM),用于在文本文件开头使用,这可以用于字节顺序检测(或字节序检测)。 - Robert R Evans
8
不要为UTF-8编写BOM!“Unicode标准既不要求也不建议在UTF-8中使用BOM。”http://en.wikipedia.org/wiki/Byte_order_mark - Roddy
这篇文章是关于更新主题“Microsoft C/C++编译器中管理字符集的新选项”的好文章。https://blogs.msdn.microsoft.com/vcblog/2016/02/22/new-options-for-managing-character-sets-in-the-microsoft-cc-compiler/ - Yarkov Anton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接