Use goto to handle error - C Statement

C examples for Statement:goto

Description

Use goto to handle error

Demo Code

#include <stdio.h> 
#include <stdlib.h> 

int main() { // w  w  w .  ja  va2s  . com
   FILE *pRead; 
   char name[10]; 
   char hobby[15]; 
   pRead = fopen("hobbies.dat", "r"); 
   if ( pRead == NULL ) 
      goto ErrorHandler; 
   else { 
      printf("\nName\tHobby\n\n"); 
      fscanf(pRead, "%s%s", name, hobby); 
      while ( !feof(pRead) ) { 
         printf("%s\t%s\n", name, hobby); 
         fscanf(pRead, "%s%s", name, hobby); 
      }
   }
   exit(EXIT_SUCCESS); //exit program normally 
   ErrorHandler: 
        perror("The following error occurred"); 
        exit(EXIT_FAILURE); //exit program with error 
}

Result


Related Tutorials