Answer the question
In order to leave comments, you need to log in
Writing classes to a binary file - how to fix the error?
There is a class
class data
{
public:
float N;
float* ti;
data()
{
N=0;
ti = new float[1];
ti[0]=0;
}
~data(void);
};
count = 3;
data d;
d.N=count;
d.ti=new float[count];
for(int i=0;i<count;i++)
{
d.ti[i]= 5-i;
}
ofstream out("C:\\1\\bd.dat",ios::binary|ios::out);
out.write((char*)&d,sizeof d);
out.close();
data s;
ifstream in("C:\\1\\bd.dat",ios::binary|ios::in);
in.read((char*)&s,sizeof s);
in.close();
for(int i=0;i<s.N;i++)
{
cout << "ti [ << i << "] = " << s.ti[i];
}
Answer the question
In order to leave comments, you need to log in
Read about pointers. When I first got a computer, I wanted to share the game with a friend and copied a shortcut from my desktop onto a floppy disk. Of course, this idea was doomed to failure. Your code is trying to do roughly the same thing. In the binary representation of the data class, there is one float N field that is successfully written to the file, and the second float *ti, which is just an address. After you read data from a file, it points to some place in memory where it could be anything but the array you expect it to be.
And you can fix it like this . We write the data for clarity in a text file.
Only POD types can be written this way. And the pointer makes your class a non-POD.
Although in fact, even POD structures cannot be written that easily, because structures (and classes, of course) have such a thing as field alignment. And this very alignment can differ on different platforms, for different compilers, and even the same compiler can change the alignment depending on the settings. And you can also remember endianess.
As an option, look towards protobuf, all these problems have already been solved there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question