typestar

errno and perror in C

When a call fails, errno says why, and perror prints it with your prefix.

#include <errno.h>
#include <stdio.h>
#include <string.h>

int open_or_report(const char *path) {
    errno = 0;
    FILE *f = fopen(path, "r");
    if (f == NULL) {
        perror("fopen");
        fprintf(stderr, "  (%s: %s)\n", path, strerror(errno));
        return 0;
    }
    fclose(f);
    return 1;
}

How it works

  1. Set errno to zero before the call you intend to test.
  2. perror writes to stderr; strerror gives you the text.
  3. Only check errno after a call that reported failure.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
261
Tokens
80
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 3 of 3 in Positioning & streams, step 11 of 12 in Files & I/O.

← Previous Next →