Investigate 15.6.
In Section 9.3, we learned that C interprets variables with the value of zero as false. Do you think that a null pointer will be interpreted as true or false?
fopen() returns a special value if it is not able to open the file for some reason. That special value is a NULL pointer.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile;
int num;
ifile = fopen("my_first_file_misspelled.txt", "r");
fscanf(ifile, "%d", &num);
printf("I read the number %d from the file.\n", num);
fclose(ifile);
/* The 'right' way... */
/*
ifile = fopen("my_first_file_misspelled.txt", "r");
if (ifile == NULL) {
printf("File not found!! Exiting.\n");
} else {
fscanf(ifile, "%d", &num);
printf("I read the number %d from the file.\n", num);
fclose(ifile);
}
*/
return(0);
}
fopen() returning a value of NULL) there is no need to close the file. In fact, even attempting to close the file in this case would lead to a runtime error: feel free to try it out!