C library - strerror() function



The C library strerror() function takes one parameter that searches an internal array for the error number which is errnum and returns a pointer to an error message string. The error strings produced by strerror depend on the developing platform and compiler.

Syntax

Following is the syntax of the C library strerror() function −

char *strerror(int errnum)

Parameters

This function accepts only a single parameter.

  • errnum − This is the error number, usually errno.

Return Value

This function returns a pointer to the error string describing error errnum.

Example 1

Following is the C library program that demonstrates the usage of strerror() function.

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

int main () {
   FILE *fp;

   fp = fopen("file.txt","r");
   if( fp == NULL ) {
      printf("Error: %s\n", strerror(errno));
   }
   
   return(0);
}

Output

On executing the above program, it will produce result like we are accessing to open a file but the file doesn't exists −

Error: No such file or directory
Advertisements