Easy Tutorial
❮ C Function Sprintf C Examples Sum Array ❯

C Library Function - perror()

C Standard Library - <stdio.h>

Description

The C library function void perror(const char *str) outputs a descriptive error message to the standard error stderr. It first outputs the string str followed by a colon and then a space.

Declaration

Here is the declaration for the perror() function.

void perror(const char *str)

Parameters

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the perror() function.

#include <stdio.h>

int main ()
{
   FILE *fp;

   /* First rename the file */
   rename("file.txt", "newfile.txt");

   /* Now let's try to open the same file */
   fp = fopen("file.txt", "r");
   if( fp == NULL ) {
      perror("Error: ");
      return(-1);
   }
   fclose(fp);

   return(0);
}

Let's compile and run the above program, which will produce the following result because we are trying to open a file that does not exist:

Error: : No such file or directory

C Standard Library - <stdio.h>

❮ C Function Sprintf C Examples Sum Array ❯