I am writing an unknown number of structs to a binary file and then reinterpret_cast-ing the bytes back to the struct. I know how to write the bytes.
I am unsure how to iterate over the binary file. I would like to use std::ifstream. At some point I must need to increment a file pointer/index by sizeof(struct) bytes, but the only examples (of reading binary in to structs) I could find online were writing N structs and then reading N structs, they were not looping over the file, incrementing any file index.
Pseudo code of what I would like to achieve is:
std::ifstream file("test.txt", std::ifstream::binary);
const size_t fileLength = file.size();
size_t pos = 0;
while(pos < fileLength)
{
MyStruct* ms = &(reinterpret_cast<MyStruct&>(&file[pos]));
// Do whatever with my struct
pos += sizeof(MyStruct);
}
UPDATE:
My struct is POD