I have a file which contains two columns, name of students and
average. I would like to read in the name and average,
re-calculate the new average based on the latest test score and
write the new average to the file. I know how to do the first two
parts (reading the name and average and calculating the new
average). How do I do the last part, i.e. write the new average to
the file?
here is a sample file
---------------------------------
#comment: this is a sample file
student1 average1
student2 average2
student3 average3
This sounds like the general problem of replacing text in a text file,
which is addressed briefly in the FAQ for comp.lang.c, link in my
signature.
It is possible to do this directly if and only if the new text is
exactly the same length as the original text. File systems are not
like word processors or editors. They do not provide a method of
shoving the rest of the text down if you write more in the middle, or
pulling the rest of the file up if you take something out.
The standard way to do something like this is to create a new file for
writing with a temporary name, one you make up or one generated by the
standard tmpnam() function. Then open your original file for reading.
Read from the original file line-by-line, perhaps using fgets(), make
whatever modifications you need to the data, and write it to the new
file most likely with fputs() or fprintf().
When you have finished, fclose() both files. Either remove() or
rename() the original file (perhaps to some pattern used for back up
files), then rename() the new file to the name of the original.
This method handles modifications where deletions and additions are
different sizes or in different parts of the file.
All of the functions I mentioned are prototyped in <stdio.h>.