0
0
Cprogramming~5 mins

perror and strerror functions

Choose your learning style9 modes available
Introduction

These functions help show error messages when something goes wrong in your program. They make it easier to understand what caused the problem.

When a file cannot be opened and you want to tell the user why.
When a network connection fails and you want to explain the error.
When a system call returns an error and you want to print a readable message.
When debugging your program to find out what caused an error.
When logging errors to a file for later review.
Syntax
C
void perror(const char *s);

char *strerror(int errnum);

perror prints your message s followed by a colon and the error description for the current errno.

strerror returns a string describing the error number you give it.

Examples
This prints: "File open error: " to standard error.
C
perror("File open error");
This prints the error message string for the current errno value.
C
printf("Error: %s\n", strerror(errno));
This prints the message for the error number ENOENT (usually "No such file or directory").
C
int err = ENOENT;
printf("Error message: %s\n", strerror(err));
Sample Program

This program tries to open a file that does not exist. It uses perror to print the error message, then prints the same message using strerror.

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

int main() {
    FILE *f = fopen("nonexistent.txt", "r");
    if (!f) {
        perror("Failed to open file");
        printf("Using strerror: %s\n", strerror(errno));
        return 1;
    }
    fclose(f);
    return 0;
}
OutputSuccess
Important Notes

errno is a global variable set by system calls and some library functions when an error happens.

Always include <errno.h> and <string.h> to use these functions.

perror prints directly to standard error, while strerror returns a string you can use anywhere.

Summary

perror prints an error message with your text and the system error.

strerror returns a string describing an error number.

Use these to make your program's errors clear and easy to understand.