我在 C++ 中有一个 float 数组,我想将它保存到一个二进制文件中(以节省空间),以便以后能够再次读取它。为此,我编写了以下代码来编写数组:
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(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(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;
}
}
}
我是否错误地读取或写入了数据?我读取的数据是否有问题?
看看这两行:
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);
Tôi là một lập trình viên xuất sắc, rất giỏi!