C++,将 vector<char> 写入 ofstream 会跳过空格

标签 c++ stl ofstream

尽管我尽了最大的努力,但我似乎无法在此处找到错误。我正在写一个 vector 到 ofstream。该 vector 包含二进制数据。但是,由于某种原因,当应该写入空白字符(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 被省略,表面上是因为它是空白。

如有任何建议,我们将不胜感激。

最佳答案

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

关于C++,将 vector<char> 写入 ofstream 会跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9305183/

相关文章:

c++ - 将托管字节数组转换为非托管字符串

c++ - 获取控件周围的 "padding"

STL - 在使用 STL 集容器时将 "using namespace std"添加到代码中时调用哪个 find() 函数?

c++ - 映射运算符 [] 和 bool 作为值

c++ - 带有 ifstream 和 ofstream 的可变文件名

c++ - ofstream 名称中的变量

c++ - 一般如何从 void * 指针动态转换?

c++ - 如何访问 iPod/iPhone 上的图片文件?

c# - 将 STL/C++/CLI 容器传递给 .Net

c++ - 将 boost::multiprecision 数据类型写入二进制文件