我在c++中有一个浮点数组,我希望将它保存到一个二进制文件中(以节省空间),并能够在以后再读取它。为此,我编写了以下代码来编写数组:
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();然后,我立即重新打开该文件,以检查数据是否保存正确:
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();但是,当我检查这两个数组是否相等时,我得到了非常不同的值:
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;
}
}
}我的数据读错了还是写错了?我所读的数据的转换有什么问题吗?
发布于 2016-04-07 01:46:11
看看这两行:
ofstream zOut(string(outFile).append("_geom.txt", ios::out | ios::binary));
ifstream zIn(string(outFile).append("_geom.txt"), ios::in | ios::binary);在我看来,第一行似乎有一个错误。也许你的意图是
ofstream zOut(string(outFile).append("_geom.txt"), ios::out | ios::binary);https://stackoverflow.com/questions/36465257
复制相似问题