CodeBlanks Logo Icon CodeBlanks

Summary - Error handling

  • C course
  • Intermediate
  • Lesson 58/116
  • 5 min

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.

Practice 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");.

Starter code

main.c
#include <stdio.h>
// Include errno.h and assert.h

// read_first_line: assert, fopen, perror, fgets, printf, fclose

int main(void) {
    return read_first_line("missing.txt");
}

Sample solution

main.c
#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");
}

Expected output

cannot open: No such file or directory

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If fopen returns NULL, which is best?

  • Ignore and continue
  • Call assert
  • Print errno with printf
  • Print error with perror and exit Correct answer

Explanation: perror writes context and reason to stderr; exiting is safe.

2 Match tools to purpose

Term Meaning
errno Error code
perror stderr message
strerror Error string
assert Precondition check

All lessons in Intermediate