Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

file-io

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.

like image 880
karyboy Avatar asked Sep 04 '11 15:09

karyboy


1 Answers

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.

like image 98
Eli Iser Avatar answered Oct 21 '22 23:10

Eli Iser