C Error Handling in Files
In this page:
Handling NULL file pointers
This check should happen immediately after every fopen() call, before any other file operation is attempted, since every subsequent function assumes it's working with a valid, open file stream.
Example: Handling NULL file pointers
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
printf("Failed to open file");
return 1;
}
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using ferror() to detect errors
ferror() only reports that something went wrong on a previous operation; it doesn't tell you what specifically failed, so it's typically combined with perror() or checking errno for more detail.
Example: Using ferror() to detect errors
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "test");
if (ferror(fp)) {
printf("Error occurred");
} else {
printf("No error");
}
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Checking for EOF with feof()
feof() only becomes true after an attempted read has failed due to running out of data -- checking it before that read attempt will incorrectly report that you haven't reached the end yet, even on the very last byte.
Example: Checking for EOF with feof()
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hi");
fclose(fp);
fp = fopen("data.txt", "r");
char buffer[10];
while (fgets(buffer, 10, fp) != NULL) {}
printf("%d", feof(fp));
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Clearing error indicators with clearerr()
This is useful when you want to attempt an operation again after fixing whatever caused the original error, since the error and EOF flags otherwise persist and can block further operations on that stream.
Example: Clearing error indicators with clearerr()
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "test");
clearerr(fp);
printf("%d", ferror(fp));
fclose(fp);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using perror() for detailed file errors
Unlike a generic error message, perror() automatically appends the system's actual explanation for the failure (like 'No such file or directory' or 'Permission denied'), which is far more useful for debugging than a bare NULL check alone.
Example: Using perror() for detailed file errors
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
perror("File open failed");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: