Perror c – perror C Library Function

Perror c: The function void perror(const char *str); prints a error message to stderr (the standard error output stream, usually the console). First the string str is printed, followed by a colon and a space then the generated error description is printed followed by a newline character (‘\n’). The error message generated by perror is platform specific.

Function prototype of perror

void perror(const char *str);
  • str : This is the pointer to a C string containing a custom error message to be printed before the error message itself.

Return value of perror

NONE

C program using perror function

C perror: The following program shows the use of perror function to show a custom message in case of an error. This program tries to open a file “randomFile.txt”, which doesn’t exist in current directory. As a result, it will set the value of errno.

perror C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   int ch;
    
   /* Trying to open a file for reading 
      which doesn't exists */
   file = fopen("randomFile.txt","r");
   if(file == NULL){
      perror("Error Unable to open a file");
      return(1);
   } else {
      printf("Success: File opened for reading\n");
   }
    
   return(0);
}

Output

Error Unable to open a file: No such file or directory