Lesson 55: Error Handling: errno and perror
In C, many standard library functions (especially I/O and system calls) signal failure by returning a special value (like NULL for fopen or -1 for system calls). They simultaneously set a global integer variable, errno, to indicate why the failure occurred.
The errno Variable
- Defined in
<errno.h>. - It is set by system calls and library functions upon failure.
- Its value is a coded integer representing the specific error type (e.g., 'File not found', 'Permission denied').
Crucial: errno is only meaningful immediately after a function fails. Its value is not guaranteed to be preserved across unrelated successful calls.
The perror() Function
perror() prints a descriptive error message to stderr (Standard Error) based on the current value of errno. It allows you to prefix the error message with a custom string.
Syntax: void perror(const char *s);
Example: File Open Error
c #include <stdio.h> #include <errno.h>
int main() { FILE *fp;
// Trying to open a non-existent file for reading
fp = fopen("nonexistent.dat", "r");
if (fp == NULL) {
// Use perror to print a descriptive error message
perror("File Operation Failed");
// The output might look like:
// File Operation Failed: No such file or directory
return 1;
}
fclose(fp);
return 0;
}
strerror()
The strerror() function (in <string.h>) returns a pointer to the human-readable string corresponding to a given error number, which is useful if you want to log the error message instead of immediately printing it.