Hi all,
[code snippet appended at the end.)
my question:
A class has a few string variables with not know length at design
time.
Now I declare lets say a 1000 of those classes and put them in a vector.
Can I write that vector directly to a binary file?
(.wright((char *)&vector,sizeof (vector)))
Currently I write the classes to the file (iterate over the vector).
As a safety I write the length of the variable strings before the class
so that when I read the file I can create a string thats large enough,
using: .resize(length_of_string,'\0')
The code that I wrote works. If I leave a function out namely
files.clear();Could someone explain why it breaks?
Improvement on the code itself is always welcome.
My system:Linux 2.6 gnu compiler.
This is the code snipped that I wrote:
FileDes is the class with three strings (declared as "string")
the normal members functions are present get*data*, set*data*, operator<*>,...
ItsFile is declared as fstream in the class datafile (again a class with
normal member functions.)
void
datafile::ReadFromFile (vector < FileDes > &vecfd)
{
FileStatus (input, open); // opens a file in binary mode for input
int length, a, b, c;
//read the size of the vector.
//why? so only one (re)allocation is needed
ItsFile.read ((char *) &length, sizeof length);
vecfd.reserve (length);
for (int i = 0; i < length; i++) //reading from a file
{
//read the length of the 3 strings first:
ItsFile.read ((char *) &a, sizeof a);
ItsFile.read ((char *) &b, sizeof b);
ItsFile.read ((char *) &c, sizeof c);
FileDes temp(a,b,c) ; //expand strings to hold enough data
FileDes temp; //works also. does string expand automatically
//in this situation(or code)
//read the class and add to the vector
ItsFile.read ((char *) &temp, sizeof temp);
//if the program breaks it happens on the next line:
vecfd.push_back (temp);
}
}
int
main ()
{
datafile Filed;
int length;
vector < FileDes > files;
vector< FileDes > filesa;
Filed.GetFileList (files);
Filed.WriteToFile (files);
//The above all works fine checked it with displaying the strings when
//I knew what it had to contain
files.clear();//if left out the program works.
//if present it breaks at run time,
// executing the next line of code.
//break point in void datafile::ReadFromFile... at vecfd.push_back (temp);
Filed.ReadFromFile (filesa);
/*
DO SOME STUFF
*/
return 0;
}