Reputation: 187
I have an array of float in c++ and I would like to save it to a binary file (to save space) and to be able to read it again later. To do this, I wrote the following code to write the array:
float *zbuffer = new float[viewport[3]*viewport[2]*4];
//.....
//.. populate array
//.....
ofstream zOut(string(outFile).append("_geom.txt", ios::out | ios::binary));
zOut.write(reinterpret_cast<char*>(zBuffer), sizeof(float)*viewport[3] * viewport[2] * 4);
zOut.close();
And I re-open the file immediately afterwards to check that the data was saved correctly:
ifstream zIn(string(outFile).append("_geom.txt"), ios::in | ios::binary);
float *chBuffer = new float[viewport[3] * viewport[2] * 4];
zIn.read(reinterpret_cast<char*>(chBuffer), sizeof(float)*viewport[3] * viewport[2] * 4);
zIn.close();
However, when I check the two arrays for equality, I get wildly different values:
for (int i = 0; i < viewport[3]; i++)
{
for (int j = 0; j < viewport[2]; j++)
{
int idx = 4 * (i*viewport[2] + j);
if ((zBuffer[idx] != chBuffer[idx]) || (zBuffer[idx + 1] != chBuffer[idx + 1]) || (zBuffer[idx + 2] != chBuffer[idx + 2])) {
cout << "1: " << zBuffer[idx] << " " << zBuffer[idx + 1] << " " << zBuffer[idx + 2] << endl;
cout << "2: " << chBuffer[idx] << " " << chBuffer[idx + 1] << " " << chBuffer[idx + 2] << endl;
}
}
}
Am I reading or writing the data wrongly? Are there any problems with the casting of the data I read?
Upvotes: 0
Views: 3437
Reputation: 1473
Just look at these two lines:
ofstream zOut(string(outFile).append("_geom.txt", ios::out | ios::binary));
ifstream zIn(string(outFile).append("_geom.txt"), ios::in | ios::binary);
It seems to me that there is a typo in the first line. Maybe the intended is
ofstream zOut(string(outFile).append("_geom.txt"), ios::out | ios::binary);
Upvotes: 2