Re: Save a vector inside a structure.
Jensen Somers wrote:
Hello,
Is it possible to save a vector inside a structure to a file?
Yes, if you do the hard work of saving the contents of the vector
yourself (or if you let a serialisation package do it).
Let's say I have the following piece of code:
struct SaveData
{
int first,
int last,
std::vector<int> order;
};
If I write the structure to a binary file and read it out again the
data which should be in the vector is totally corrupt (other variables
are fine).
That is to be expected.
std::vector<> uses dynamically allocated memory to store the vector
elements, but the fwrite/fread functions (which I suspect you used)
don't know about that. They will simply write/read
sizeof(std::vector<int>) bytes, which amounts to only the bookkeeping
data that std::vector<> uses.
At this moment I should be able to define a fixed size for
that vector (but I have no idea if that will work),
No, that won't work, unless you meant turning the std::vector<> into a
fixed-sized array.
but in the future
the size of the vector will change and I don't want this to be fixed.
I also need to be able to store the entire SaveData structure, looping
through the vector and saving each value one by one is not an option
as I also need to be able to save on some EEPROM and as far as I
understand that I'm only able to use entire structures.
Looping over the elements is the only way you can store the contents of
the vector.
As EEPROM and binary files don't care about the structure of the data
written to them, you can copy the contents of the structure to an array
of (unsigned) char, and then write that array in one go to the final
destination.
something like this could work (not tested or even compiled):
unsigned char* serialise_SaveData(SaveData* in)
{
static unsigned char buf[EEPROB_BLOCK_SIZE];
unsigned char *p = buf;
size_t num_elements = in->order.size();
memcpy(p, &in->first, sizeof(in->first));
p += sizeof(in->first);
memcpy(p, &in->last, sizeof(in->last));
p += sizeof(in->last);
memcpy(p, &num_elements, sizeof(num_element));
p += sizeof(num_elements);
for (int i=0; i<num_elements; i++)
{
int temp = in->order[i];
memcpy(p, &temp, sizeof(temp));
p += sizeof(temp);
}
return buf;
}
Note: This in not production-quality code. Error checking is left as an
exercise.
I haven't found a lot of information regarding this subject so if
anyone has any ideas or suggestions, please enlighten me.
You could take a look on the subject of serialisation.
- Jensen
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]