M
M
Microdel2014-05-14 22:47:06
C++ / C#
Microdel, 2014-05-14 22:47:06

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);
};

I create a class element and write it to a binary file
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();

I close the program, open it again, then read it
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]; 
  }

When I try to display the ti array, I get an error (0xc0000005), how can I fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2014-05-15
@Microdel

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.

K
kosmos89, 2014-05-15
@kosmos89

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 question

Ask a Question

731 491 924 answers to any question