Section 15.7 Writing to a File
So far we have read data from files. It is just as easy to write data to a file. The main differences to reading are:
- Use "w" (as in writing) in the
fopen()
statement instead of "r" (as in reading). - Use
fprintf()
to write to the file instead offscanf()
to read from the file.
When writing to a file, the first step is to open the file using:
fopen(filename, "w");
Note that if the file does not exist prior to this command then it will be created. If it does exist already, then the existing file will be overwritten without any warning (you might lose important data this way!!).
Another way to write to a file is to open it for “appending”:
fopen(filename, "a");
This appends data to the file at its end (if the file exists) and otherwise creates a new file. Take a look at this example: