如何可移植地写std :: wstring到文件? [英] How to portably write std::wstring to file?

查看:222
本文介绍了如何可移植地写std :: wstring到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 wstring 这样声明:

// random wstring
std::wstring str = L"abcàdëefŸg€hhhhhhhµa";

这个文字是UTF-8编码的,因为我的源文件是。

我非常希望将其转换为文件读取(当文本编辑器设置为正确的编码时)

I would very much like to get this into a file reading (when text editor is set to the correct encoding)

abcàdëefŸg€hhhhhhhµa

code> ofstream 不是很合作(拒绝采用 wstring 参数)和 wofstream 据说需要知道区域设置和编码设置。我只想输出这组字节。

but ofstream is not very cooperative (refuses to take wstring parameters), and wofstream supposedly needs to know locale and encoding settings. I just want to output this set of bytes. How does one normally do this?

编辑:必须是跨平台,不应依赖于UTF-8编码。我只是碰巧有一组字节存储在 wstring ,并希望输出它们。它很可能是UTF-16或纯ASCII。

It must be cross platform, and should not rely on the encoding being UTF-8. I just happen to have a set of bytes stored in a wstring, and want to output them. It could very well be UTF-16, or plain ASCII.

推荐答案

为什么不把文件写成二进制。只需使用stream与std :: ios ::二进制设置。编辑器应该能够解释它。不要忘记开头的Unicode标志0xFEFF。
您可能更喜欢使用库编写,请尝试下列方法之一:

Why not write the file as a binary. Just use ofstream with the std::ios::binary setting. The editor should be able to interpret it then. Don't forget the Unicode flag 0xFEFF at the beginning. You might be better of writing with a library, try one of these:

http://www.codeproject.com/KB/files/EZUTF.aspx

http://www.gnu.org/software/libiconv/

http://utfcpp.sourceforge.net/

这篇关于如何可移植地写std :: wstring到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆