Frederik said:
Hi all,
I'm trying to do some C programming, but I need some help. I'm reading
a textfile [fread(...)]. When some sequence of characters is being
read, the file must not be read anymore, but instead I want to write
to it after those characters. How do I have to do this: Should I first
fclose the file and open it again or should I use read + write access?
And if I close the file first, how can I find the correct position
again where I left of? Is there a way to truncate the file? Many silly
questions I guess.
Open with mode "r+" (or "rb+") instead of mere "r" ("rb").
When you've read as far as you want, fseek(fptr, 0, SEEK_CUR) --
this seems at first sight to be a no-op, but you must call a
positioning function when "reversing directions" from input to
output lest the implementation's internal buffers and suchlike
become confused. After the fseek(), start writing.
NOTE: This will not discard the pre-existing characters
that came after what you read, but will overwrite them. If
you don't overwrite all of them, the tail end of the the file
will still exist and still contain the original characters;
this sequence of operations does not truncate the file. For
example, if the file was originally 1000 characters long and
you read 100 characters and then overwrite 200 characters, the
result will be a file with three "zones:" 100 original characters
at the beginning, 200 new characters in the middle, and 700
original characters at the end.
If you want to get rid of those 700 trailing characters,
I can think of three possibilities:
- Instead of reading and then overwriting, read and copy
the first 100 characters to a new file and then write
200 characters to the new file. You can leave the old
file untouched, or you can fclose() both streams, delete()
the old file, and rename() the new to the old.
- If you know of a character (or sequence of characters)
that cannot possibly appear as data, write that character
or characters after the 200 new characters. All the
programs that read the file should treat this special
sequence as a pseudo-EOF. The <=699 trailing characters
will still be present in the file, but you'll ignore them.
- Use a non-Standard function to truncate the file, but be
aware that not all systems provide such functions and that
there may be subtle differences among systems that do.