C programming stdio.h function - void perror(const char *str)
The perror
function in the stdio.h
library of the C programming language is used to print a descriptive error message to the standard error stream (stderr
) based on the value of the errno
variable. The syntax of the perror
function is as follows:
void perror(const char *str);
Here, the argument str
is a string to be printed before the error message. If str
is NULL
, only the error message is printed.
The perror
function prints a descriptive error message to the standard error stream, based on the value of the errno
variable. The errno
variable is a global variable defined in the errno.h
library that contains the last error code generated by a system or library call. The perror
function prints a message that describes the error represented by the errno
value, along with the string str
, if provided. If errno
is zero, no message is printed.
For example, the following code attempts to open a file that does not exist, and uses the perror
function to print the error message:
#include <stdio.h> #include <errno.h> int main() { FILE *fptr; fptr = fopen("nonexistent.txt", "r"); if (fptr == NULL) { perror("Error"); return 1; } fclose(fptr); return 0; }
In this example, the fopen
function attempts to open the file "nonexistent.txt"
for reading. Since the file does not exist, the function returns NULL
, indicating an error. The code in the if
statement is executed, and the perror
function is called to print the error message "Error: No such file or directory"
, along with the string "Error"
. The program then returns with an error code of 1.