C library Macro - errno

Advertisements


Description

The C library macro extern int errno set by system calls and some library functions in the event of an error to indicate what went wrong.

Declaration

Following is the declaration for errno macro.

extern int errno

Parameters

  • NA

Return Value

  • NA

Example

The following example shows the usage of errno Macro.

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

extern int errno ;

int main ()
{
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp == NULL ) 
   {
      fprintf(stderr, "Value of errno: %d\n", errno);
      fprintf(stderr, "Error opening file: %s\n", strerror(errno));
   }
   else 
   {
      fclose(fp);
   }
   
   return(0);
}

Let us compile and run the above program, this will produce the following result in case file file.txt does not exist:

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


Advertisements
Advertisements