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

C Error Handling in Files

File error handling means checking whether opening, reading, or writing worked, like making sure a door opened before walking in. C gives you tools to detect and describe what went wrong.
Syntax
c
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

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

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

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

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

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 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;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking whether the file pointer is NULL after fopen.
  2. Using while (!feof(fp)) as the loop condition, which processes the last line twice.
  3. Not calling clearerr when reusing a stream after an error or EOF.
Chapter Summary
  • File handling starts with fopen() to open a file and fclose() to close it.
  • fread(), fwrite(), fprintf(), and fscanf() read and write binary or formatted data.
  • fseek() and ftell() 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:

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.