Updating ASCII files in c
Hi
I have to write a program in C, in which I need to open a text file for reading and writing. I want to insert in the text a string as a new row, between 2 existing rows. The problem is, when I use r+, w+ or a+ as arguments in the fopen function, I cannot perform properly the above action, without destroying the current data in the file.
Is there a way in C to do that?
Thanks in advance for your time.
[433 byte] By [
gstavrin] at [2007-11-20 11:20:03]

# 2 Re: Updating ASCII files in c
I want to insert in the text a string as a new row, between 2 existing rows.
You've defined (well implied) several steps that the disk system isn't designed to do 'for you' - you have to write something that does this yourself.
In other words, there's NO disk operation that inserts data into a file, scooting existing data downwards. Any illusion that such a thing happens is an illusion created by someone writing the function as STLDude suggests.
I just wanted to dispel any expectation that you were in search of something that's there to be found. It's not there.
You have to do the 'scooting' - which is basically a re-writing of the data below your insertion point.
One thing you could do, in Windows or any other OS that supports this notion, is to use memory mapped files. That's a way of treating a file on disk as if it were already in RAM. You then operate upon the file as if it were memory.
However, if you're not ready for a winding road on the subject BEFORE you can begin to solve this puzzle, you may do better either with STLDude's suggestion, or something similar, like this:
Identify the point in the file were your insertion is to begin, accounting for all whitespace characters including line feeds, etc. Call this the edit point.
Read in the data from the edit point to the end of the file, store in in a character array I'll refer to as text_tail.
Write your new text started at the edit point, including line feeds, carriage returns as required, noting the length of your material. This forms the 'tail point' - which is the edit point plus the length of what you've written, including the line feeds, etc.
Now, re-write the text_tail contents starting at the tail_point.
You're done.
Of course, if the edit point was at byte zero, this degrades into STLDude's algorithm.
JVene at 2007-11-9 1:26:27 >
