Fault using seekp () to replace part of a file in binary

I am having problems replacing part of a file in binary mode. For some reason, my seekp () line does not place the file pointer at the desired position. Right now, adding new content to the end of the file instead of replacing the desired part.

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?

Thank you very much in advance.

0


source to share


2 answers


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

The following code writes an entry 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) );
}   

      

+1


source


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

      

here - you don't update the number or write - so basically you go through the whole file and write to "some" location (pos is not located)



And Neil Butterworth is right (posted when I typed 8)) it seems like you missed smth

0


source







All Articles