6.2 File Validation
When opening a file for reading, the file must exist and the user must have appropriate permissions to access if. If the file does not exist or the user does not have access to it, the file can not be opened. To determine if a file was opened successfully, you should check the value returned by the fopen function.
- infile = fopen("data.txt", "r");
- if(!infile) {
- printf("Error: The input file can not be opened.\n");
- exit(1);
- }
The fopen function returns a null pointer when there is an error opening the specified file in the given access mode.
When a file is opened for writing, the a new file is created if the file does not already exist. If it does exist, the file is cleared. As with reading from a file, the user must have write permissions on the directory in which you are trying to open a new file for writing. Thus, you should also verify that the output file was opened successfully before attempting to write to it
- outfile = fopen("report.txt", "w");
- if(!outfile) {
- printf("Error: The output file can not be opened.\n");
- exit(1);
- }

If you try to use a file variable for a file that could not be opened, the program will abort with a run-time error. Programming best practices suggest that it is better to exit the program cleanly by calling the exit function instead of letting the program abort abnormally.