C library - errno Macro



The C library errno Macro of type extern int is set by system calls and some library functions in the event of an error to indicate if anything went wrong.

Whenever any specific function encountered error, the system calls automatically called through this macro and is used to report the error condition in program.

Following are the list of error occurs in C programs −

  • File I/O errors (e.g., file not found, permission denied)
  • Memory allocation failures (e.g., malloc() returning NULL)
  • Invalid function arguments (e.g., passes invalid file)
  • Math-related errors (e.g., division by zero)
  • Network-related errors (e.g., socket errors)

Syntax

Following is the C library syntax of the errno Macro −

extern int errno

Parameters

  • This is not a function. So, it does not accept any parameter.

Return Value

  • It doesn't return any value.

Example 1

Following is the basic C library macros errno to see its demonstration.

#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);
}

Output

On compiling of above code will produce the following result in which the filename file.txt does not exist −

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