By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,838 Members | 1,668 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,838 IT Pros & Developers. It's quick & easy.

Write in the middle of a file without overwriting

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.