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.
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
.
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.
精彩评论