I am facing a small problem. I have a struct, which has a vector. Note that the vector is dynamic per every iteration. Now, in a particular iteration, how do I store the struct which contains a vector of size n to a binary file?
Also, when retrieving, assume that I know how the size of the vector, how to I retrieve from the binary file, the struct variable containing the vector of all the stored elements?
I am able to store something to the binary file (as I can see the size increasing when writing), but when I am trying to retrieve back the elements, I am getting size of vector to be zero.
Unfortunately, I have to achieve this using the standard STL and not use any third-party libraries.
You typically serialize a vector by writing the length of the vector, followed by that number of elements. When you read it back in, having the length come first lets you know how many more items to read as part of that vector. As a simple first approximation, consider something like this:
This is open to lots of tweaks, improvements, and simple modifications -- just for example, for the moment, I've passed the vector (or whatever -- could be a std::deque, etc.) by reference rather than passing iterators. That probably simplifies most use, but doesn't fit as well with the rest of the library.
This also serializes in text format, one number per line. Discussions comparing text to binary have happened before, so I won't try to repeat all the arguments here -- I'll just note that the same basic idea can be done in binary format just as well as text.
You should have a look at Boost Serialization.
If you can't use 3rd party libraries, you must know that C++ doesn't support serialization directly. This means you'll have to do it yourself.
This article shows a nice way of serializing a custom object to the disk and retrieving it back. And this tutorial shows you how to get started right now with fstream.
This is my attempt:
EDIT: since the OP asked how to store/retrieve more than record I decided to updated the original code.
So, what changed? Now there's an array
student_t apprentice[3];
to store information of 3 students. The entire array is serialized to the disk and then it's all loaded back to the RAM where reading/searching for specific records is possible. Note that this is a very very small file (84 bytes). I do not suggest this approach when searching records on huge files.Outputs:
Dump of the binary file: