I'm guessing the error lies in the writeBinary function where I open the file everytime I write into it. I am not sure how to create the file and have it not overwrite the existing data. My code results into reading 3, 3, 3 instead of 1,2,3.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
class Binary
{
public:
Binary(int num);
~Binary();
void writeBinary();
void readBinary();
string binFile;
int value;
};
Binary::Binary(int num)
{
value = num;
binFile = "BinaryFile.bin";
}
Binary::~Binary()
{
}
void Binary::writeBinary()
{
fstream outBinaryFile;
ofstream appendFile(binFile, ios::out | ios::app);
outBinaryFile.write((char*)&value, sizeof(value));
outBinaryFile.close();
}
void Binary::readBinary()
{
ifstream inFileBinary; //declare variable
inFileBinary.open(binFile, ios::in); //open binary file to be read from
inFileBinary.read((char*)&value, sizeof(value));//read binary file
inFileBinary.close(); //close binary file
cout << value << ", ";
}
int main()
{
//need this part
Binary num1(1);
Binary num2(2);
Binary num3(3);
num1.writeBinary();
num2.writeBinary();
num3.writeBinary();
num1.readBinary();
num2.readBinary();
num3.readBinary();
return 0;
}