CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2009
    Posts
    68

    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!

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    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.

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: fstream - Writing in the middle of a file

    1) you need to open in :
    Code:
    ios::in | ios::out
    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.

  4. #4
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: fstream - Writing in the middle of a file

    Quote Originally Posted by Philip Nicoletti View Post
    1) you need to open in :
    Code:
    ios::in | ios::out
    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
  •  





Click Here to Expand Forum to Full Width

Featured