为什么我不能读取超过4094个字符的UTF-16文件?

Joa*_*sen 13 c++ linux utf-16 wstring wifstream

一些信息:

  • 我只在Linux上试过这个
  • 我和GCC(7.2.0)和Clang(3.8.1)一起尝试过
  • 根据我的理解,它需要C++ 11或更高版本

运行时会发生什么

我得到预期的字符串"abcd"重复,直到它达到4094个字符的位置.之后所有输出都是这个标志"?" 直到文件结束.

我怎么看待这个?

我认为这不是预期的行为,它必定是某个地方的错误.

你可以测试的代码:

#include <iostream>
#include <fstream>
#include <locale>
#include <codecvt>

void createTestFile() {
  std::ofstream file ("utf16le.txt", std::ofstream::binary);
  if (file.is_open()) {
    uint16_t bom = 0xFEFF; // UTF-16 little endian BOM
    uint64_t abcd = 0x0064006300620061; // UTF-16 "abcd" string
    file.write((char*)&bom,2);
    for (size_t i=0; i<2000; i++) {
      file.write((char*)&abcd,8);
    }
    file.close();
  }
}

int main() {
  //createTestFile(); // uncomment to make the test file

  std::wifstream file;
  std::wstring line;

  file.open("utf16le.txt");
  file.imbue(std::locale(file.getloc(), new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
  if (file.is_open()) {
    while (getline(file,line)) {
      std::wcout << line << std::endl;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*hik 11

这看起来像是一个库bug.逐步执行gcc 7.1.1编译的示例程序,使用gdb:

(gdb) n
28      while (getline(file,line)) {
(gdb) n
29        std::wcout << line << std::endl;
(gdb) p line.size()
$1 = 8000
Run Code Online (Sandbox Code Playgroud)

正如预期的那样读取8000个字符.但是之后:

(gdb) p line[4092]
$18 = (__gnu_cxx::__alloc_traits<std::allocator<wchar_t> >::value_type &) @0x628240: 97 L'a'
(gdb) p line[4093]
$19 = (__gnu_cxx::__alloc_traits<std::allocator<wchar_t> >::value_type &) @0x628244: 98 L'b'
(gdb) p line[4094]
$20 = (__gnu_cxx::__alloc_traits<std::allocator<wchar_t> >::value_type &) @0x628248: 25344 L'?'
(gdb) p line[4095]
$21 = (__gnu_cxx::__alloc_traits<std::allocator<wchar_t> >::value_type &) @0x62824c: 25600 L'?'
(gdb) p line[4096]
$22 = (__gnu_cxx::__alloc_traits<std::allocator<wchar_t> >::value_type &) @0x628250: 24832 L'?'
Run Code Online (Sandbox Code Playgroud)

line[4092]line[4093]看行.但后来,我看到了line[4094],line[4095]line[4096],含6300,64006500,而不是0063,00640065.

所以,这实际上是从角色4094开始搞砸了,而不是4096.我转储了二进制UTF-16文件,看起来对我来说是正确的.BOM标记之后是文件整个内容的一致字节序.

唯一令人费解的是,为什么clang和gcc都会受到影响,但谷歌的快速搜索表明clang也使用了gcc的libstdc ++,至少直到最近.所以,这对我来说就像是一个libstdc ++ bug.