我有 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"
,它永远解决了这个问题)。
但如果你想使用旧标准的多平台代码,你可以使用这种方法来编写流:
- Read the article about UTF converter for streams
- 将
stxutif.h
从上面的源代码添加到您的项目中 以 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();
然后以
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/