Home Segments Index Top Previous Next

551: Mainline

To write to a file, you proceed as though you were reading from a file, except that you use "w" as the second argument of fopen, rather than "r".

FILE* file-pointer name; 
file-pointer name = fopen(file specification, "w"); 

The following is an example for which the file pointer is named analysis_target and the file specification is "test.result":

                       File specification 
                            | 
                            v 
FILE* analysis_target;   -----------     
analysis_target = fopen("test.result", "w"); 
------------                            ^ 
    ^                                   | 
    |                              Write specification 
File-pointer name 

If you want to add data to a file that may exist already, you use "a" rather than "w". If the file does not exist, "a" acts like "w". If it does happen to exist, "a" tells C that you want your write statements to append data to the end of the existing file.