C Library - perror() function



The C library perror() function is designed to print a descriptive error message to the standard error stream (stderr), which helps in debugging and understanding what went wrong in your program.

Syntax

Following is the C library syntax of the perror() function −

void perror(const char *str);

Parameters

This function accepts only a single parameter −

  • str: A pointer to a null-terminated string that will be printed before the error message. If this string is not NULL and not empty, it will be followed by a colon and a space (: ). This string typically indicates the context or the function where the error occurred.

Return value

perror() does not return a value. It is a void function. Its primary purpose is to print an error message to stderr.

Example 1: Opening a Non-Existent File

This example tries to open a file that doesn't exist. fopen() sets errno to indicate the error, and perror() prints a descriptive message about the failure.

Below is the illustration of C library perror() function.

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

int main() {
    FILE *file = fopen("non_existent_file.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
    } else {
        fclose(file);
    }
    return 0;
}

Output

The above code produces following result−

Error opening file: No such file or directory

Example 2: Creating a File in a Non-Writable Directory

This example tries to create a file in a directory where the user does not have write permissions. fopen() fails, sets errno to EACCES, and perror() prints an appropriate error message.

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

int main() {
    FILE *file = fopen("/non_writable_directory/new_file.txt", "w");
    if (file == NULL) {
        perror("Error creating file");
    } else {
        fclose(file);
    }
    return 0;
}

Output

After execution of above code, we get the following result

Error creating file: Permission denied
Advertisements