A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_perror.htm below:

C Library - perror() function

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 −

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4