5

I'm trying to write a vector of doubles to a binary file. After doing this I want to read it. This doesn't seem to work. Here is the code:

ofstream bestand;
vector<double> v (32);
const char* pointer = reinterpret_cast<const char*>(&v[0]);
size_t bytes = v.size() * sizeof(v[0]);
bestand.open("test",ios::out | ios::binary);
for(int i = 0; i < 32; i++)
{
   v[i] = i;
   cout << i;
   }
bestand.write(pointer, v.size());
bestand.close();
ifstream inlezen;
vector<double> v2 (32);
inlezen.open("test", ios::in | ios::binary);
char byte[8];
bytes = v2.size() * sizeof(v2[0]);
inlezen.read(reinterpret_cast<char*>(&v2[0]), bytes);
for(int i =0; i < 32; i++){

 cout << endl << v2[i] << endl;
 }

This outputs "0 1 2 3 0 0 0......" so it seems it reads the first 4 numbers correctly.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
pivu0
  • 138
  • 1
  • 10

1 Answers1

7

This .write() takes the number of bytes, not the number of items to write:

bestand.write(pointer, v.size());

Since you've already computed the correct value, use it:

bestand.write(pointer, bytes );
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • This works thank you! Assume I have a for loop, writing a new vector each iteration to the same file. What do I have to change to the read? Also but this in a for loop? – pivu0 Nov 13 '12 at 17:03
  • Ok nvm I've figured it out :). Thanks – pivu0 Nov 13 '12 at 17:10