C++ – Trouble with seekp() to replace portion of file in binary mode

c++fstream

I'm having some trouble with replacing a portion of a file in binary mode. For some reason my seekp() line is not placing the file pointer at the desired position. Right now its appending the new contents to the end of the file instead of replacing the desired portion.

long int pos;
bool found = false;
fstream file(fileName, ios::binary|ios::out|ios::in);

file.read(reinterpret_cast<char *>(&record), sizeof(Person));

while (!file.eof())
{   
    if (record.getNumber() == number) {
       pos=file.tellg();
       found = true;
       break;
}

// the record object is updated here

file.seekp(pos, ios::beg); //this is not placing the file pointer at the desired place
file.write(reinterpret_cast<const char *>(&record), sizeof(Person));
cout << "Record updated." << endl;
file.close();

Am I doing something wrong?

Thanks a lot in advance.

Best Solution

I don't see how your while() loop can work. In general, you should not test for eof() but instead test if a read operation worked.

The following code writes a record to a file (which must exist) and then overwrites it:

#include <iostream>
#include <fstream>
using namespace std; 

struct P {
    int n;
};

int main() {
  fstream file( "afile.dat" , ios::binary|ios::out|ios::in);
  P p;
  p.n = 1;
  file.write( (char*)&p, sizeof(p) );
  p.n = 2;
  int pos = 0;
  file.seekp(pos, ios::beg);
  file.write( (char*)&p, sizeof(p) );
}   
Related Question