karyboy
karyboy

Reputation: 317

C++ overwriting data in a file at a particular position

i m having problem in overwriting some data in a file in c++. the code i m using is

 int main(){
   fstream fout;
   fout.open("hello.txt",fstream::binary | fstream::out | fstream::app);
   pos=fout.tellp();
   fout.seekp(pos+5);
   fout.write("####",4);
   fout.close();
   return 0;

}

the problem is even after using seekp ,the data is always written at the end.I want to write it at a particular position. And if i dont add fstream::app , the contents of the file are erased. Thanks.

Upvotes: 10

Views: 11522

Answers (2)

Rob K
Rob K

Reputation: 8926

You want something like

fstream fout( "hello.txt", fstream::in | fstream::out | fstream::binary );
fout.seek( offset );
fout.write( "####", 4 );

fstream::app tells it to move to the end of the file before each output operation, so even though you explicitly seek to a position, the write location gets forced to the end when you do the write() (that is seekp( 0, ios_base::end );).

cf. http://www.cplusplus.com/reference/iostream/fstream/open/

Another thing to note is that, since you opened the file with fstream::app, tellp() should return the end of the file. So seekp( pos + 5 ) should be trying to move beyond the current end of file position.

Upvotes: 5

Eli Iser
Eli Iser

Reputation: 2834

The problem is with the fstream::app - it opens the file for appending, meaning all writes go to the end of the file. To avoid having the content erased, try opening with fstream::in as well, meaning open with fstream::binary | fstream::out | fstream::in.

Upvotes: 16

Related Questions