Some of the errors that occurs in the files are listed below −
- Trying to read beyond end of file.
- Device over flow.
- Trying to open an invalid file.
- An invalid operation is performed by opening a file in a different mode.
Functions for error handling
The functions for error handling are as follows −
- ferror ( )
- perror ( )
- feof ( )
ferror ( )
It is for detecting an error while performing read or write operations.
The syntax is as follows −
int ferror (file pointer);
For example,
FILE *fp;
if (ferror (fp))
printf ("error has occurred”);It returns zero, if it is a success and returns as non-zero in other cases.
perror ( )
It is used for printing an error.
It shows the string that pass to it, which is followed by a colon, a space, and the text representation of current error value.
The syntax is as follows −
perror (string variable);
For example,
FILE *fp; char str[30] = ”Error is”; perror (str);
Output
Error is: error 0
Exaple
Following is the C program for usage of ferror ( ) and perror ( ) function −
#include<stdio.h>
main ( ){
FILE *fp;
char str[30] = "error is";
int i = 20;
clrscr ( );
fp = fopen ("sample. txt", "r");
if (fp = = NULL){
printf ("file doesnot exist");
} else {
fprintf (fp, "%d", i);
if (ferror (fp)){
perror (str);
printf ("error ");
}
fclose (fp);
getch ( );
}Output
When the above program is executed, it produces the following result −
Error is: Error1 compiler generated. Error.
feof ( )
It is used for checking whether an end of the file has been reached or not.
The syntax is as follows −
int feof ( file pointer);
For example,
FILE *fp;
if (feof (fp))
printf ("reached end of the file");If it returns a non-zero then, it is success. Otherwise, it is zero.
Example
Following is the C program for usage of feof ( ) function −
#include<stdio.h>
main ( ){
FILE *fp;
int i,n;
clrscr ( );
fp = fopen ("number. txt", "w");
for (i=0; i<=100;i= i+10){
putw (i, fp);
}
fclose (fp);
fp = fopen ("number. txt", "r");
printf ("file content is”);
for (i=0; i<=100; i++){
n = getw (fp);
if (feof (fp)){
printf ("reached end of file");
break;
}
else{
printf ("%d", n);
}
}
fclose (fp);
getch ( );
}Output
When the above program is executed, it produces the following result −
File content is 10 20 30 40 50 60 70 80 90 100 Reached end of the file.