【问题标题】:read and write array of float to file读取和写入浮点数组到文件
【发布时间】:2016-04-07 01:42:41
【问题描述】:

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

我是否错误地读取或写入数据?我读取的数据的转换有什么问题吗?

【问题讨论】:

  • 看起来不错。什么才算“大不相同”?

标签: c++ arrays io


【解决方案1】:

看看这两行:

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

【讨论】:

  • 天啊,真丢人。将能够在 10 分钟内接受答案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-02-22
  • 2014-10-13
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多