← Back to C Course | Chapter 10: File I/O | Lesson 6 of 6

C Error Handling in Files

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

c
#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;
}

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

c
#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;
}

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()

c
#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;
}

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()

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("data.txt", "w");
	fprintf(fp, "test");
	clearerr(fp);
	printf("%d", ferror(fp));
	fclose(fp);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	FILE *fp = fopen("nonexistent.txt", "r");
	if (fp == NULL) {
		perror("File open failed");
	}
	return 0;
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.