-
September 7th, 2012, 12:58 PM
#1
fstream - Writing in the middle of a file
Hello,
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)?
Thanks!
-
September 7th, 2012, 01:21 PM
#2
Re: fstream - Writing in the middle of a file
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.
-
September 8th, 2012, 07:39 PM
#3
Re: fstream - Writing in the middle of a file
1) you need to open in : 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
Last edited by Philip Nicoletti; September 10th, 2012 at 06:22 AM.
-
September 10th, 2012, 07:08 AM
#4
Re: fstream - Writing in the middle of a file
Originally Posted by Philip Nicoletti
1) you need to open in : 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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|