Program 63) Write a program to illustrate error handlingin file operations.
This program shows illustrates the use of the NULL pointer test and feof function. When we input filename as TETS, the function call
fopen ("TETS", "r") ;
returns a NULL pointer because the file TETS does not exist and therefore the message "Cannot open the file" is printed out.
Similarly, the call, foef(fp2) returns a nonzero integer when the entire data has been read, and hence the program prints the message "Ran out of data" and terminates further reading.
PROGRAM
#include <stdio.h>
main ( )
{
char *filename ;
FILE *fp1, *fp2 ;
int i, number ;
fp1 = fopen ("TESTA", "w") ;
for (i = 10; i <= 100; i += 10)
putw (i, fp1) ;
fclose (fp1) ;
printf ("\nInput filename\n") ;
open_file:
scanf ("%s", filename) ;
if ((fp2 = fopen (filename, "r")) == NULL)
{
printf ("Cannot open the file.\n") ;
printf ("Type filename again.\n\n") ;
goto open_file ;
}
else
for (i = 1; i <= 20; i++)
{ number = getw(fp2) ;
if (feof (fp2))
{
printf ("\nRan out of data.\n") ;
break ;
}
else
printf ("%d\n", number) ;
}
fclose (fp2) ;
}
Output: Input filename
TETS
Cannot open the file
Type filename again
TEST
10
20
30
40
50
60
70
80
90
100
Ran out of data
No comments:
Post a Comment