0
0
CHow-ToBeginner · 3 min read

How to Use perror in C: Syntax, Example, and Tips

In C, perror is used to print a descriptive error message to stderr based on the current value of errno. You call perror with a custom message string that prefixes the error description. It helps diagnose why a system or library call failed.
📐

Syntax

The perror function prints an error message to the standard error stream (stderr). It combines your custom message with a description of the current error stored in errno.

  • message: A string you provide to describe the context of the error.
  • perror appends a colon, a space, the error description, and a newline.
c
void perror(const char *message);
💻

Example

This example tries to open a file that does not exist. When fopen fails, perror prints a helpful error message showing why it failed.

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

int main() {
    FILE *file = fopen("nonexistent.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    fclose(file);
    return 0;
}
Output
Error opening file: No such file or directory
⚠️

Common Pitfalls

Common mistakes when using perror include:

  • Calling perror without a meaningful message, which makes debugging harder.
  • Not checking the return value of functions that set errno before calling perror.
  • Using perror after errno has been overwritten by another call.

Always call perror immediately after the failing function to get the correct error.

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

int main() {
    FILE *file = fopen("nonexistent.txt", "r");
    if (file == NULL) {
        // Wrong: no message
        perror("");

        // Right: descriptive message
        perror("Failed to open nonexistent.txt");
        return 1;
    }
    fclose(file);
    return 0;
}
Output
Failed to open nonexistent.txt: No such file or directory
📊

Quick Reference

Use this quick guide when working with perror:

UsageDescription
perror("message")Prints 'message: ' followed by error description from errno.
Call perror immediately after failureEnsures errno is accurate.
Use a clear messageHelps identify where the error happened.
Output goes to stderrSeparates error messages from normal output.

Key Takeaways

Use perror to print clear error messages based on errno after a failure.
Always provide a descriptive message to perror for easier debugging.
Call perror immediately after the function that sets errno to avoid incorrect errors.
perror outputs to stderr, keeping errors separate from normal program output.