Re: fopen: pre-pending text
- From: Floyd Davidson <floyd@xxxxxxxxxx>
- Date: Sat, 28 Jan 2006 16:22:06 -0900
Kasper Dupont <10067397463153721693@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
>"Floyd L. Davidson" wrote:
>> joe.user0@xxxxxxxxx wrote:
>> >So how do I insert (pre-prend) text with fopen?
>You can't do that, so you'll have to write all of it again
>either to a new file or to the same one.
>> 1) open original file for reading
>> 2) open a temp file for writing
>> 3) write new text to temp file
>> 4) write original file to end of temp file
>> 5) close both files
>I assume you intend to check error codes from those calls.
That goes without saying. "Open" means a *lot* more than just
calling the open(2) function.
>> 6) verify temp file (using stat or whatever) has desired data
>An error shouldn't go undetected until this point? Of course
Never said that. It's just that at this point, if everything
has apparently "worked", there is no reason (and not real substitute)
for some type of data integrity check.
>someone might have modified the orignal (or even the copy)
>in the meantime. But such modification may as well happen
>right after verifiying.
Yep. Of course I suspect that a 12 step program probably scared
the OP enough. Trying to explain something like file locking might
be too much? Or maybe I should have...
>> 7) open temp file for reading
>> 8) open original file for writing at start of file
>> 9) write temp file to original file
>> 10) close both files
>> 11) verify original file now has new data
>> 12) unlink temp file
>Step 7-12 could be replaced by a single rename call. Of
>course you'd need to ensure that they are on the same file
>system. But that can almost be guaranteed by putting the
>temp file in the same directory as the orignal.
The point is to be *positive* that the new file is valid (step
11), before deleting the verified copy (step 12).
Granted that, as I noted (but you did not quote) in the original
post, much of the above can be done without if the the data is
not that critical.
Floyd L. Davidson http://www.apaflo.com/floyd_davidson
Ukpeagvik (Barrow, Alaska) floyd@xxxxxxxxxx