The clearerr() function defined in the stdio.h header file. It helps to reset the End of File(EOF) indicator and the error flag associated with the stream pointed by the specified stream.
int fclose(FILE *stream); #where stream should be a file pointer
The clearerr() function takes a single parameter. Using the perror() function we can find out the exact nature of the error. The message displayed by the function is the actual error.
Parameter | Description | Required / Optional |
---|---|---|
stream | the pointer to a FILE object that identifies the stream | Required |
If an invalid stream is passed the return value of clearerr() function should be -1 and set errno to EBADF.
Input | Return Value |
---|---|
Invalid stream | return -1 |
#include <stdio.h>
int main()
{
FILE *pnt;
char ch;
pnt = fopen("file.txt", "w");
ch = fgetc(pnt);
if( ferror(pnt) ) {
printf("Reading error from the file : file.txt\n");
}
clearerr(pnt);
if( ferror(pnt) ) {
printf("Reading error from the file : file.txt\n");
}
fclose(pnt);
return(0);
}
Output:
Reading error from the file "file.txt"
#include <stdio.h>
int main (){
FILE * pnt;
pnt = fopen("testfile.txt","r");
if (pnt==NULL) perror ("Error in opening file");
else {
fputc ('x',pnt);
if (ferror (pnt)) {
printf ("Error in writing to testfile.txt\n");
clearerr (pnt);
}
fgetc (pnt);
if (!ferror (pnt))
printf ("No errors in reading testfile.txt\n");
fclose (pnt);
}
return 0;
}
Output:
Error in writing to testfile.txt No errors in reading testfile.txt