Using perror for descriptive errors
What you'll learn: How to use the perror function to print human-readable explanations of why a file operation failed.
The mystery of the failing file
When you try to open a file in C using fopen and it returns NULL, you know something went wrong—but you don't know what. Did the file not exist? Was it locked by another program? Did you lack permission to read it?
Instead of guessing, C provides a globally accessible variable called errno that stores a numeric error code whenever a system call fails. However, looking up a code like 2 or 13 is tedious. This is where perror (short for "print error") comes in. It translates that cryptic number into a plain English sentence.
How perror works
Think of perror like a helpful librarian. If you ask for a book and they can’t find it, they don't just point to a generic "Error" sign; they tell you, "The shelf is empty" or "Someone else checked this out."
When you call perror, you pass it a string (usually the name of the function that failed). The function then prints your string, followed by a colon, and then the specific reason for the failure.
Seeing it in action
Here is how you use it when attempting to open a file that might not exist:
#include <stdio.h>
int main() {
FILE *fptr;
// Attempting to open a file that doesn't exist
fptr = fopen("missing_document.txt", "r");
if (fptr == NULL) {
// perror automatically looks at the global error state
// and prints a descriptive message to the console.
perror("Error opening file");
return 1;
}
fclose(fptr);
return 0;
}
If missing_document.txt is not there, your console will display:
Error opening file: No such file or directory
Why use it?
Using perror is a best practice because it makes your programs professional and easy to debug. Instead of your program simply crashing or doing nothing, it tells you exactly what the operating system is complaining about. It saves you from writing dozens of if statements to check for every possible failure scenario manually.
Key takeaway
Use perror immediately after a file operation fails to print a clear, human-readable explanation of the error.