C
Summary - Error handling
Combine errno, perror and assert to write a robust file reader.
Summary - Error handling
In this group you learned four tools: errno for the error code, perror for the stderr message, strerror for the error string and assert for precondition checks. Together you'll write a robust file reader.
The pattern: open with fopen, if it returns NULL, write the error with perror and exit. Reset errno; check it after the call. Use assert for parameter preconditions. This pattern is standard in real C projects; every call is checked, every error is reported.
A robust file reader
A robust file reader does three layers of checks: catch the primary failure via the return value (fopen NULL), report the secondary cause with errno and strerror, and verify preconditions with assert. This way it gives a meaningful message to users and catches programmer errors early.
In the example below, the read_first_line function opens the file, reads the first line and reports errors with perror. The assert(filename != NULL) precondition catches a programmer error. You can write your own file helpers by mimicking this pattern.
Exercise Write a robust file reader
Include <stdio.h>, <errno.h> and <assert.h>. Write int read_first_line(const char *filename): check the precondition with assert(filename != NULL);, open with FILE *f = fopen(filename, "r");, on failure if (f == NULL) { perror("cannot open"); return 1; }. Read with char buf[64]; fgets(buf, sizeof(buf), f);, print printf("%s", buf);, close with fclose(f); and return 0;. In main, call return read_first_line("missing.txt");.
Show example solution
#include <stdio.h>
#include <errno.h>
#include <assert.h>
int read_first_line(const char *filename) {
assert(filename != NULL);
FILE *f = fopen(filename, "r");
if (f == NULL) {
perror("cannot open");
return 1;
}
char buf[64];
fgets(buf, sizeof(buf), f);
printf("%s", buf);
fclose(f);
return 0;
}
int main(void) {
return read_first_line("missing.txt");
}
Test yourself
-
If fopen returns NULL, which is best?
- Ignore and continue
- Call assert
- Print errno with printf
- Print error with perror and exit
Show answer
Print error with perror and exit — perror writes context and reason to stderr; exiting is safe.
-
Match tools to purpose
- errno
- Error code
- perror
- stderr message
- strerror
- Error string
- assert
- Precondition check
Next lesson: Headers and sources