Search code examples
c++binaryiterationifstreamofstream

Reading list of objects from binary file


I am currently building a custom binary file for a huge list of data which will be representing some angle of movements in a game. Although i am running into a wall when trying to find a way to write all the datapoints and then reading them into a huge array or vector.

Here is how i constructed my fileformat:

class TestFormat {
    public:
        float   x;
        float   y;
        float   z;
};

And the test code for writing and reading:

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

To extend this code i can just write the additional objects into the same file, but i am not sure how to load these objects back into an array afterwards.


Solution

  • You could do something like this:

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

    Using Peter Barmettler's suggestion:

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