C ++ rewriting data to a file in a specific place

im has a problem with overwriting some data in a file in C ++. used code i m

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; 

}

problem even after using seekp, data is always written at the end. I want to record it in a specific place. And if I do not add fstream :: app, the contents of the file will be erased. Thanks.

+6
source share
2 answers

The problem with fstream::app is that it opens the file for adding, that is, all entries go to the end of the file. To avoid erasing content, try opening with fstream::in , that is, opening with fstream::binary | fstream::out | fstream::in fstream::binary | fstream::out | fstream::in fstream::binary | fstream::out | fstream::in .

+8
source

Do 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 if you are explicitly looking for a position, the recording location will be forced to end when you execute write() (this is seekp( 0, ios_base::end ); ).

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

One more note: if you opened the file with fstream::app , tellp() should return the end of the file. Therefore, seekp( pos + 5 ) should try to go beyond the current position of the file.

+2
source

Source: https://habr.com/ru/post/896594/


All Articles