c++ - 读写 float 组到文件

标签 c++ arrays io

我在 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/

相关文章:

c++ - CPU 松弛指令和 C++11 原语

php - 关联数组中的单个 mysql 字段

python - 尝试从包含奇怪字符的文件中读取某些文本。 (Python)

javascript - 使用JavaScript,我可以上传一个word文件并使用.replace然后另存为新文档吗

c++ - 正确的 C++ 方法来存储多类型数据

c++ - 为什么在删除一个函数时,在函数参数中使用指定初始值设定项的这段代码从不明确变为不编译?

javascript - 为什么 Math.pow(0, 0) === 1?

ios - 获取数据但无法正确显示

php - 拆分嵌套数组以在 php 中使用

c - 无法让子进程相互通信