Write in the middle of a file without overwriting

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ellixis

    Write in the middle of a file without overwriting

    Hello,

    How can I use fwrite() and fseek() in order to write data in the
    middle (or anywhere else) of a file without overwriting existing data
    ?

    People told me that I should load the file into memory (a variable)
    and use concatenation.

    But, according to me, It isn't clean to load an entire file into
    memory... Imagine a huge file of 5 GB !!!

    Thanks,

    --
    Helix
  • Andy Hassall

    #2
    Re: Write in the middle of a file without overwriting

    On 15 May 2004 12:39:04 -0700, helix@phpbb-fr.com (Ellixis) wrote:
    [color=blue]
    >How can I use fwrite() and fseek() in order to write data in the
    >middle (or anywhere else) of a file without overwriting existing data
    >?
    >
    >People told me that I should load the file into memory (a variable)
    >and use concatenation.
    >
    >But, according to me, It isn't clean to load an entire file into
    >memory... Imagine a huge file of 5 GB !!![/color]

    Whatever happens, you're going to have to rewrite the file from the point at
    which you insert data, up to the end of file.

    If there's going to be 5Gb of data maybe you ought to take a step back and
    think whether you really should be editing a huge file like this, what's the
    context of the problem?

    As far as doing it without hammering memory, something like:

    (1) Open file in read/write mode
    (2) Seek to the point where you want to write
    (3) Read out a block of existing data from the file of the same length as the
    data you want to insert, to set up a buffer for the later step.
    (4) Seek back to the point where you want to write.
    (5) Write the new data. You'll now be at the end of the new data, and have to
    start shuffling the old data up the file:
    (7) Read a chunk of data from the file, and append it to the buffer.
    (8) Seek back to start of chunk, and write a chunk from the beginning of the
    buffer.
    (9) Repeat (7)+(8) until end of file, then write the remainder of the buffer to
    the end of file.

    --
    Andy Hassall <andy@andyh.co. uk> / Space: disk usage analysis tool
    http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space

    Comment

    Working...