gpt4 book ai didi

c++ - 如何使用 C++ 在 Windows 上写入和读取 UTF 16 文件

转载 作者:可可西里 更新时间:2023-11-01 11:08:57 26 4
gpt4 key购买 nike

SO 上有很多关于此的问题,但大多数都没有提到将 wstring 写回文件。例如,我发现这个是为了阅读:

// open as a byte stream
std::wifstream fin("/testutf16.txt", std::ios::binary);
// apply BOM-sensitive UTF-16 facet
fin.imbue(std::locale(fin.getloc(),
new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
// read
std::wstring ws;
for(wchar_t c; fin.get(c); )
{
std::cout << std::showbase << std::hex << c << '\n';
ws.push_back(c);
}

我尝试过类似的写作方式:

    std::wofstream wofs("/utf16dump.txt", std::ios::binary);
wofs.imbue(std::locale(wofs.getloc(),
new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
wofs << ws;

但它会产生垃圾,(或者 Notpad++ 和 vim 无法解释它)。如标题 Im on Win, native C++, VS 2010 中所述。

输入文件:

t€stUTF16✡
test

这是结果:

t€stUTF16✡
test

转换为十六进制:

0000000: 7400 ac20 7300 7400 5500 5400 4600 3100  t.. s.t.U.T.F.1.
0000010: 3600 2127 0d00 0a00 7400 6500 7300 7400 6.!'....t.e.s.t.
0000020: 0a
...

vim 正常输出:

t^@¬ s^@t^@U^@T^@F^@1^@6^@!'^M^@ ^@t^@e^@s^@t^@

编辑:我最终使用了 UTF8。 Andrei Alexandrescu 说这是最好的编码,所以没有太大损失。 :)

最佳答案

您的类似 代码——不是。你删除了 std::ios::binary 风格,尽管 the documentation

The byte stream should be written to a binary file; it can be corrupted if written to a text file.

ASCII 模式下的 NL->CRLF 转换不会对 UTF-16 文件做任何漂亮的事情,因为它会插入一个字节 0x0D 而不是两个字节 0x00 0x0D。

关于c++ - 如何使用 C++ 在 Windows 上写入和读取 UTF 16 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com