CodeBlanks Logo Icon CodeBlanks

perror

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

Learn to print error messages with perror.

The perror function

perror writes the errno message to stderr. Usage: perror("cannot open file");. The output combines your prefix, a colon and the system message: cannot open file: No such file or directory.

perror reads errno and prints its text. You don't need strerror to write the message; perror does both. It's the fastest path in debugging because it gives context (prefix) and reason in one line.

stderr and perror

perror writes to stderr, not stdout. This matters: when program output is piped to another program, errors still show on screen. stderr is unbuffered; it appears at once.

perror's format is: your prefix, then a colon, then a space and the errno message. If you don't want a prefix, write perror(""); or perror(NULL);; the system message still prints.

Practice Print a file error with perror

Assign fopen("missing.txt", "r") to FILE *f. If f == NULL, call perror("cannot open file"); and return 1;. Otherwise print printf("open\n"); and close with fclose(f);. End with return 0;.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Open missing.txt with fopen
    // If NULL, call perror and return 1
    // Else printf and fclose
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    FILE *f = fopen("missing.txt", "r");
    if (f == NULL) {
        perror("cannot open file");
        return 1;
    }
    printf("open\n");
    fclose(f);
    return 0;
}

Expected output

cannot open file: No such file or directory

Questions and answers

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

1 Complete the perror call

Question
FILE *f = fopen("missing.txt", "r");
if (f == NULL) ____("cannot open file");
Answer
FILE *f = fopen("missing.txt", "r");
if (f == NULL) perror("cannot open file");

Explanation: perror writes prefix and system message to stderr.

2 Where does perror write its output?

  • To stdout
  • To a file
  • To syslog
  • To stderr Correct answer

Explanation: perror writes errors to stderr, so piping doesn't hide them.

3 Match perror output parts

Term Meaning
Prefix Your text
: Separator
System message errno meaning
stderr Output stream

All lessons in Intermediate