gpt4 book ai didi

c++ - 读写 float 组到文件

转载 作者:行者123 更新时间:2023-11-28 05:44:38 28 4
gpt4 key购买 nike

我在 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<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;
}
}
}

我是否错误地读取或写入了数据?我读取的数据是否有问题?

最佳答案

看看这两行:

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);

关于c++ - 读写 float 组到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36465257/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com