c ++如何在unicode / utf8中写入/读取ofstream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5026555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ how to write/read ofstream in unicode / utf8
提问by user63898
I have UTF-8 text file , that I'm reading using simple :
我有 UTF-8 文本文件,我正在使用 simple 阅读:
ifstream in("test.txt");
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.
现在我想创建一个新文件,它将是 UTF-8 编码或 Unicode。我怎样才能做到这一点ofstream
或其他?这将创建 ansi 编码。
ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
回答by Yarkov Anton
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).
好的,关于便携式变体。这很容易,如果你使用C++11
标准(因为有很多额外的包含,比如"utf8"
,它永远解决了这个问题)。
But if you want to use multi-platform code with older standards, you can use this method to write with streams:
但是如果你想使用具有旧标准的多平台代码,你可以使用这种方法来编写带有流的代码:
- Read the article about UTF converter for streams
- Add
stxutif.h
to 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();
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...
- 阅读有关流的 UTF 转换器的文章
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...