I want to edit the contents of a file using fstream, but none of the modes in the fstream constructor work for me.
If I use ios::trunc, then the whole file is deleted - but I want to retain the contents and edit it.
If I use ios::app, then I can only add data to the end of the file - but I want to edit the data in the middle of the file.
If I use ios::ate, then the whole file is deleted again, similar to ios::trunc.
How can I create an fstream object without deleting the contents of the file, whilst still being able to move the pointer arbitrarily around in the file with seekp() (and not just placing it at the end as with ios::app)?
You can't. If you're editing a file, typically you'll read from the original and write to a temp, then delete the original and rename the temp to the original name - or, read the entire contents of the file into memory, modify the contents in memory, then delete and recreate the file you're editing.
2) Over-writing data in the middle of a file is done all the time.
It is simplest if the records are fixed length.
3) that being the case, you should also open in binary mode. ...
Code:
ios::in | ios::out | ios::binary
4) Normally, you would do unformatted I/O, not formatted I/O
Overwriting formatted data isn't the same as overwriting variable length data and inserting and deleting lines of text, which is what I assume the OP is talking about.
Bookmarks