How to write vector in binary fail?

Did some one know how to write vector, which is inside a class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class v{
   vector<int> a;
public:
   void read();
  void write();
};

void v::write()
{
fp.open("ivan.a",ios::binary|ios::out)
if(!fp)
 exit(1);
fp.write((char*)this,sizeof(this);
fp.close();
}

void v::read()
{
fp.open("ivan.a",ios::binary|ios::in)
if(!fp)
 exit(1);
fp.read((char*)this,sizeof(this);
fp.close();
}


But I cant read from the fail when i write it with these function.
Can someone tell where is the problem?
Where is fp declared?
You cannot binary dump the class to a file.

vector<> contains pointers. You are dumping the pointers to file rather than the actual elements of the vector.
A couple of functions for doing proper binary I/O can be found here:
http://www.cplusplus.com/forum/beginner/11431/page1.html#msg53963

To write your vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdexcept> 
...

#include "duoas-binary-io.hpp"
using namespace little_endian_io;

...

void v::write()
  {
  ofstream f( "ivan.a", ios::binary );
  if (!f) throw std::runtime_error( "Could not open file \"ivan.a\"!" );  // don't halt your program, just complain 

  for (unsigned n = 0; n < a.size(); n++)
    write_word( f, a[ n ] );

  f.close();
  }

Hope this helps.
to kbw:
Class can be write in binary file like that:
fp.write((char*)this,sizeof(this));
and can be read like that
fp.write((char*)this,sizeof(this));
but it,s work only with static data. If it's dinamic like vector really i must use example of Duoas, but then i must write and the size of the vector, to know after that how exactly records i have in the fail and read it. Can some one give me idea how read vector exclude to write it size ih the fail
Topic archived. No new replies allowed.