【发布时间】:2016-04-15 20:31:17
【问题描述】:
我目前正在为大量数据构建一个自定义二进制文件,这些数据将代表游戏中的某个运动角度。虽然我在尝试找到一种方法来写入所有数据点然后将它们读入一个巨大的数组或向量时遇到了困难。
这是我构建文件格式的方式:
class TestFormat {
public:
float x;
float y;
float z;
};
以及读写测试代码:
int main()
{
TestFormat test_1, temp;
test_1.x = 4.6531;
test_1.y = 4.7213;
test_1.z = 6.1375;
// Write
ofstream ofs("test.bin", ios::binary);
ofs.write((char *)&test_1, sizeof(test_1));
ofs.close();
// Read
ifstream ifs("test.bin", ios::binary);
ifs.read((char *)&temp, sizeof(temp));
ifs.close();
cout << temp.x << endl;
}
要扩展此代码,我可以将其他对象写入同一个文件,但我不确定之后如何将这些对象加载回数组中。
【问题讨论】:
-
你只是写了,然后读了,一个。所以不止一个人这样做?
-
提示:如果一个对象占用M个连续字节,那么N个这样的对象的数组占用N×M个连续字节。
-
我明白你在说什么。但是如何使用
read函数读取多个对象呢?
标签: c++ binary iteration ifstream ofstream