C ++,将向量<char>写入ofstream跳过空白</char>

时间:2012-02-16 03:33:17

标签: c++ stl ofstream

尽管我付出了最努力的努力,但我似乎无法找到这里的错误。我正在向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正在被忽略,表面上是因为它是空白。

任何建议都将不胜感激。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

使用boost::serializationboost::archive::binary_oarchive是一种更有效的方法,而不是直接编写矢量&lt;&gt; s。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

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

相关问题