C Error Handling in Files
In this page:
FILE *file_pointer = fopen("filename.txt", "mode");
if (file_pointer == NULL) {
// handle the error
}
if (ferror(file_pointer)) {
// a read or write failed
}
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
// Check whether fp == NULL
if (fp == NULL) {
// Print formatted text to the screen
printf("Failed to open file");
// Send 1 back to the caller
return 1;
}
fclose(fp);
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "test");
// Check whether ferror(fp)
if (ferror(fp)) {
// Print formatted text to the screen
printf("Error occurred");
} else {
// Print formatted text to the screen
printf("No error");
}
fclose(fp);
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
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) {}
// Print formatted text to the screen
printf("%d", feof(fp));
fclose(fp);
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "test");
clearerr(fp);
// Print formatted text to the screen
printf("%d", ferror(fp));
fclose(fp);
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
// Check whether fp == NULL
if (fp == NULL) {
perror("File open failed");
}
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
- Not checking whether the file pointer is
NULLafterfopen. - Using
while (!feof(fp))as the loop condition, which processes the last line twice. - Not calling
clearerrwhen reusing a stream after an error or EOF.
- File handling starts with
fopen()to open a file andfclose()to close it. fread(),fwrite(),fprintf(), andfscanf()read and write binary or formatted data.fseek()andftell()move through a file, and you should check for errors when working with files.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: