w3resource

C perror() function

C library function - perror()

The perror() function is used to print an error message to stderr based on the error state stored in errno. The string pointed to by string, followed by a colon and a space, is printed to the standard error stream if string is not NULL.

Syntax:

void perror(const char *str)

Parameters:

Name Description Required /Optional
str Contains a custom message. Required

Return value

  • This function does not return any value.

Example: The following example shows the usage of perror() function.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
   FILE *fh;
 
   if ((fh = fopen("test1.txt","r")) == NULL)
   {
      perror("Can not open the said file.");
   }
   return 0;
}

Output:

Can not open the said file.: No such file or directory

C Programming Code Editor:

Previous C Programming: C puts()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdio/c_library_method_perror.php