【问题标题】:Can I write single byte to a file without temporary variable?我可以将单个字节写入没有临时变量的文件吗?
【发布时间】:2019-07-25 13:57:33
【问题描述】:

我有一个简单的调试函数,它将字节写入将显示为图像的文件。它遵循ppm 格式。

原来我是这样用的:

static void SaveDebugImage(const std::string& filePath, const unsigned char* psdata, const int resolution)
{
  // Debug: print stored data in file
  std::ofstream file;
  file.open(filePath, std::ios::out | std::ios::binary);
  if (!file.is_open())
  {
    // Throws error and crashes the program on purpose
    RError("[ImageDebug::SaveDebugImage] Cannot write to %s", filePath.c_str());
  }

  file << "P6"
    << "\n"
    << resolution << "\n"
    << resolution << "\n"
    << "255"
    << "\n";

  const char zero = 0;
  for (int i = 0; i < resolution * resolution; ++i)
  {

    file.write(reinterpret_cast<const char*>(pxdata), sizeof(*pxdata));
    ++pxdata;
    file.write(reinterpret_cast<const char*>(pxdata), sizeof(*pxdata));
    ++pxdata;
    file.write(&zero, sizeof(zero));
    ++pxdata;
  }
  file.flush();
  file.close();
}

你可以看到它跳过了颜色的最后一个字节,这是因为数据不是严格的 RGB 图像,而是一种元信息格式。 R、G 和 B 通道的含义不是颜色。您还可以观察到对const char zero = 0 的需求,我必须使用它来写零。

我现在手头有一个真正提供表面颜色的函数,它可能看起来像这样:

OurLibrary::Color getRealColor(byte r, byte g, byte b);

现在假设这个虚构的Color 类有一个unsigned char getR() const 方法,我如何在没有临时变量的情况下将结果写入文件。现在我必须这样做:

OurLibrary::Color pixelColor(getRealColor( ... ));
const unsigned char colorR = pixelColor.getR();
file.write(reinterpret_cast<const char*>(&colorR), sizeof(colorR));

我更喜欢:

file.write(pixelColor.getR());

有没有这样的方法?我在文档中找不到它。

【问题讨论】:

  • 仅供参考,我认为在.close 之前调用.flush 是多余的?
  • getR 是按引用还是按值返回?如果它通过引用返回,则直接使用它。
  • @NathanOliver 更新问题,它返回一个值。
  • @Yksisarvinen 不会添加字符串表示吗?我以二进制格式书写 - 每种颜色 1 个字节。
  • 最简单的选择是更改getR 以通过引用返回。然后你可以使用file.write(reinterpret_cast&lt;const char*&gt;(&amp;pixelColor.getR()), sizeof(pixelColor.getR()));

标签: c++ ofstream ppm


【解决方案1】:

the documentationput“插入一个字符”。

所以,简单地说:

file.put(pixelColor.getR());

(您可能需要转换为 char 以避免一些缩小转换警告;不确定。)


另外,flush() 完全没有意义。 C++ 流在关闭时刷新。

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 2015-01-08
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多