c++ how to write/read ofstream in unicode / utf8(c ++如何在unicode/utf8中写入/读取ofstream)
问题描述
我有 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:
- 阅读有关流的 UTF 转换器的文章一个>
- 将
stxutif.h从上述来源添加到您的项目 以ANSI模式打开文件并将BOM添加到文件的开头,如下所示:
- Read the article about UTF converter for streams
- Add
stxutif.hto your project from sources above 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...
这篇关于c ++如何在unicode/utf8中写入/读取ofstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c ++如何在unicode/utf8中写入/读取ofstream
基础教程推荐
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
