【问题标题】:C++, Writing vector<char> to ofstream skips whitespaceC ++,将vector<char>写入ofstream会跳过空格
【发布时间】:2012-02-16 03:33:16
【问题描述】:

尽管我尽了最大的努力,但我似乎无法在此处找到错误。我正在向 ofstream 写入一个向量。该向量包含二进制数据。但是,由于某种原因,当应该写入空白字符(0x10、0x11、0x12、0x13、0x20)时,它被跳过了。

我尝试过使用迭代器,以及直接的 ofstream::write()。

这是我正在使用的代码。我已经注释掉了我尝试过的其他一些方法。

void
write_file(const std::string& file,
           std::vector<uint8_t>& v)
{
  std::ofstream out(file, std::ios::binary | std::ios::ate);

  if (!out.is_open())
    throw file_error(file, "unable to open");

  out.unsetf(std::ios::skipws);

  /* ostreambuf_iterator ...
  std::ostreambuf_iterator<char> out_i(out);
  std::copy(v.begin(), v.end(), out_i);
  */

  /* ostream_iterator ...
  std::copy(v.begin(), v.end(), std::ostream_iterator<char>(out, ""));
  */

  out.write((const char*) &v[0], v.size());
}

编辑:以及读取它的代码。

void
read_file(const std::string& file,
          std::vector<uint8_t>& v)
{
  std::ifstream in(file);
  v.clear();

  if (!in.is_open())
    throw file_error(file, "unable to open");

  in.unsetf(std::ios::skipws);

  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(),
      std::back_inserter(v));
}

这是一个示例输入:

30 0 0 0 a 30 0 0 0 7a 70 30 0 0 0 32 73 30 0 0 0 2 71 30 0 0 4 d2

这是我读回来时得到的输出:

30 0 0 0 30 0 0 0 7a 70 30 0 0 0 32 73 30 0 0 0 2 71 30 0 0 4 d2

如您所见,0x0a 被省略了,表面上是因为它是空格。

任何建议将不胜感激。

【问题讨论】:

  • 显示你读回的代码。
  • 你读取的代码是什么样的?问题可能就在那里...
  • 你在写之前检查过vector的内容是否真的是你所期望的吗? (例如,输入步骤可能是删除空格...)
  • 你能告诉我们文件的十六进制转储吗?请不要使用您的程序,而是使用十六进制编辑器或hexdump。
  • 您是否尝试过使用write 而不是流式传输? out.write(&amp;v[0], v.size())

标签: c++ stl ofstream


【解决方案1】:

您忘记在 read_file 函数中以二进制模式打开文件。

【讨论】:

    【解决方案2】:

    比起直接写vectors,boost::serialization是一种更有效的方式,使用boost::archive::binary_oarchive。

    【讨论】:

      【解决方案3】:

      我认为 'a' 被视为换行符。我仍然需要考虑如何解决这个问题。

      【讨论】:

      • 这正是我的想法。
      【解决方案4】:

      istream_iterator 在设计上会跳过空格。尝试用这个替换你的 std::copy:

      std::copy(
          std::istreambuf_iterator<char>(in),
          std::istreambuf_iterator<char>(),
          std::back_inserter(v));
      

      istreambuf_iterator 直接转到 streambuf 对象,这将避免您看到的空白处理。

      【讨论】:

        猜你喜欢
        • 2011-11-06
        • 1970-01-01
        • 2015-07-25
        • 2014-03-22
        • 2012-04-27
        • 1970-01-01
        • 2015-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多