I’ve read a few posts on Stack Overflow and a number of other site about writing vectors to files. I’ve implemented what I feel is working, but I’m having some troubles. One of the data members in the struct is a class string, and when reading the vector back in, that data is lost. Also, after writing the first iteration, additional iterations cause a malloc error. How can I modify the code below to achieve my desired ability to save the vector to a file, then read it back in when the program launches again? Currently, the read is done in the constructor, write in destructor, of a class who’s only data member is the vector, but has methods to manipulate that vector.
Here is the gist of my read / write methods. Assuming vector<element> elements…
Read:
ifstream infile;
infile.open("data.dat", ios::in | ios::binary);
infile.seekg (0, ios::end);
elements.resize(infile.tellg()/sizeof(element));
infile.seekg (0, ios::beg);
infile.read( (char *) &elements[0], elements.capacity()*sizeof(element));
infile.close();
Write:
ofstream outfile;
outfile.open("data.dat", ios::out | ios::binary | ios_base::trunc);
elements.resize(elements.size());
outfile.write( (char *) &elements[0], elements.size() * sizeof(element));
outfile.close();
Struct element:
struct element {
int id;
string test;
int other;
};
In C++, memory can not generally be directly read and written to disk directly like that. In particular, your
struct elementcontains astring, which is a non-POD data type, and therefore cannot be directly accessed.A thought experiment might help clarify this. Your code assumes that all your
elementvalues are the same size. What would happen if one of thestring testvalues was longer than what you’ve assumed? How would your code know what size to use when reading and writing to disk?You will want to read about serialization for more information about how to handle this.