I have vector of structs:
typedef struct
{
uint64_t id = 0;
std::string name;
std::vector<uint64_t> data;
} entry;
That I want to write to file:
FILE *testFile = nullptr;
testFile = fopen("test.b", "wb");
However the normal method for read/write
fwrite(vector.data(), sizeof vector[0], vector.size(), testFile);
fread(vector.data(), sizeof(entry), numberOfEntries, testFile);
does not work as the size of entry can vary wildly depending on the contents of
std::string name;
std::vector<uint64_t> data;
so I would like methods and pointers about how to do read/writing of this data to/from files.
When dealing with non-fixed size data it's important to keep track of the size somehow. You can simply specify the amount of fixed size elements or byte size of whole structure and calculate needed values when reading the struct. I'm in favour of the first one though it can sometimes make debugging a bit harder.
Here is an example how to make a flexible serialization system.
This is a tedious job and there are already libraries that do it for you like Google's Flatbuffers, Google's Protobuf or a single header BinaryLove3. Some of them work out of the box with aggregate types (meaning all member variables are public). Here is an example of BinaryLove3 in action.