469,636 Members | 1,555 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,636 developers. It's quick & easy.

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
Jul 17 '05 #1
1 7013
On 15 May 2004 12:39:04 -0700, he***@phpbb-fr.com (Ellixis) wrote:
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 !!!


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 <an**@andyh.co.uk> / Space: disk usage analysis tool
http://www.andyh.co.uk / http://www.andyhsoftware.co.uk/space
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Gregor Lingl | last post: by
12 posts views Thread by Radek Maciaszek | last post: by
16 posts views Thread by nephish | last post: by
5 posts views Thread by anas.hashmi | last post: by
10 posts views Thread by rohit | last post: by
1 post views Thread by Curious | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.