C Standard Library

C <stdio.h> - perror() Function



The C <stdio.h> strerror() function interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the explanatory message specified in str.

The error message produced by perror() is formed by concatenating the following components:

  • If the parameter str is not a null pointer, str is printed followed by ": ".
  • The implementation-defined error message is printed followed by a newline character ('\n'). This error message string is identical to the result of strerror(errno).

perror() should be called right after the error was produced, otherwise it can be overwritten by calls to other functions.

Syntax

void perror ( const char * str );

Parameters

str Specify a pointer to a null-terminated string (C-String) with explanatory message to be printed before the error message itself. If it is a null pointer, no preceding explanatory message is printed, but the error message is still printed.

Return Value

None.

Example 1:

The example below shows the usage of perror() function.

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

int main(){
  double result = log(0.0);
  printf("%f\n", result);

  if (errno == ERANGE) {
    printf("Value of errno: %d", errno);
    perror("log(0.0) failed");
  }
}

The output of the above code will be:

-inf
Value of errno: 34
log(0.0) failed: Numerical result out of range

Example 2:

The example below the perror() function is used to describe an error when the input argument is out of domain of a mathematical function.

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

int main(){
  double result = sqrt(-1.0);
  printf("%f\n", result);

  if (errno == EDOM) {
    printf("Value of errno: %d", errno);
    perror("sqrt(-1.0) failed");
  }
}

The output of the above code will be:

-nan
Value of errno: 33
sqrt(-1.0) failed: Numerical argument out of domain

Example 3:

Consider one more example where this function is used to describe an error when tried to open a file which does not exist.

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

int main(){
  FILE * pFile;
  pFile = fopen ("wrongfile.txt", "r");
  
  if (pFile == NULL){
    fprintf(stderr, "Value of errno: %d\n", errno);
    perror("Error printed by perror");
    fprintf(stderr, "Error opening file: %s\n", strerror(errno));
  } else {
    fclose (pFile);
  }
}

The output of the above code will be:

Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

❮ C <stdio.h> Library