10

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.

karyboy
  • 317
  • 1
  • 5
  • 22

2 Answers2

15

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.

Eli Iser
  • 2,788
  • 1
  • 19
  • 29
  • but isnt fstream::in for reading from stream ,how will i be able to write to the stream using that? – karyboy Sep 04 '11 at 15:58
  • 2
    If you use both `fstream::in` and `fsteam::out` you'll open the file for reading and writing - meaning it will be opened for writing without deleting the previous content. – Eli Iser Sep 04 '11 at 16:02
5

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.

Rob K
  • 8,757
  • 2
  • 32
  • 36