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

后端 未结 2 1551
旧时难觅i
旧时难觅i 2020-12-29 11:50

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         


        
相关标签:
2条回答
  • 2020-12-29 12:10

    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.

    0 讨论(0)
  • 2020-12-29 12:18

    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.

    0 讨论(0)
提交回复
热议问题