【问题标题】:Reading list of objects from binary file从二进制文件中读取对象列表
【发布时间】: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


【解决方案1】:

你可以这样做:

  vector<TestFormat> test;
  //....
  // Read
  ifstream ifs("test.bin", ios::binary);
  while(ifs.read((char *)&temp, sizeof(temp))){
     //tmp to array
     test.push_back(TestFormat(temp));
  } 
  ifs.close();

使用 Peter Barmettler 的建议:

ifstream ifs("test.bin", ios::binary);
ifs.seekg(0, std::ios::end);
int fileSize = ifs.tellg();
ifs.seekg(0, std::ios::beg);

vector<TestFormat> test(fileSize/sizeof(TestFormat)); 
ifs.read(reinterpret_cast<char*>(test.data()), fileSize);
ifs.close();

【讨论】:

  • 这是一个有趣的解决方案。虽然它似乎在读取最后一个条目两次?
  • 是的。我不知道为什么。但是,在使用矢量的情况下,您可以忽略重复项或弹出它。
  • 最后一个对象上的重复项我仍然不明白。
  • 我修改了while循环的方法。现在,不会读取重复项。这是因为 good() == false 只会在读取失败后发生。然而此时,最后一个 temp 将在 while 评估之前再次被推入向量中。
【解决方案2】:

例如,如果你有条目,你可以这样做:

std::vector<TestFormat> temp(2);

ifstream ifs("test.bin", ios::binary);
ifs.read((char *)temp.data(), temp.size()*sizeof(TestFormat));
ifs.close();

cout << temp[1].x << endl;

【讨论】:

  • 那么像阿德里亚诺卡拉菲尼这样的东西就是要走的路。或者您将条目数放在文件的标题中。
猜你喜欢
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2015-07-27
相关资源
最近更新 更多