附加和读取二进制文件

时间:2016-09-29 00:34:22

标签: c++ binary append

我很困惑我的代码中的哪个地方出错了。而不是得到1,2,3,输出是1,1,1。关于我能做什么的任何建议?我猜我的错误在于写入数据或我使用变量值。

class Binary
{
 public:
   Binary(int num);
  ~Binary();

  void createBinary();
  void writeBinary();
  void readBinary();

  string binFile;
  int value;
  fstream binaryFile;
};

Binary::Binary(int num)
{
 value = num;
 binFile = "BinaryFile.bin";
}

Binary::~Binary()
{
}

void Binary::createBinary()
{
  binaryFile.open(binFile, ios::out | ios::binary);
  binaryFile.close();
}

void Binary::writeBinary()
{
  if (!binaryFile) //if file does not exist
  {
    createBinary();
  }

  binaryFile.open(binFile, ios::app | ios::binary);
  binaryFile.write((char*)&value, sizeof(value));
  binaryFile.close();
}

void Binary::readBinary()
{

  binaryFile.open(binFile, ios::in |ios::binary);
  binaryFile.read((char*)&value, sizeof(value));
  binaryFile.close();

  cout << value << ", ";
}



int main()
{
  Binary num1(1);
  Binary num2(2);
  Binary num3(3);

  num1.writeBinary();
  num2.writeBinary();
  num3.writeBinary();

  num1.readBinary();
  num2.readBinary();
  num3.readBinary();


  return 0;
}

1 个答案:

答案 0 :(得分:0)

由于您使用单个文件并从每个Binary():: readBinary()开始读取,因此您的结果符合预期。为每个对象使用不同的文件。

// In general we may need some random part in name but for this special case,
// since you are just writing / reading value, the following seems to work.

Binary::Binary(int num)
{
    value = num;
    binFile = "BinaryFile";    // common start
    binFile += std::to_string(value);    // differentiator
    binFile += ".bin";    // extension
}

或者,如果您想使用相同的文件,请尝试从静态变量获取帮助,以便不要一次又一次地读取同一行。