The clearerr
function is part of the <stdio.h>
header file in C. It takes in a single parameter: a filestream
.
It is used to clear the end-of-file and error indicators for the given stream.
Error indicator is stored in the
errno
variable defined in<errno.h>
header file.
The illustration below shows how clearerr
works:
The clearerr
function is defined as follows:
void clearerr(FILE *stream);
It takes a filestream
as a parameter.
The function does not return anything. Hence, the return type is void
.
The following code snippet shows how we can use the clearerr
function:
We create a file named
file.txt
. Since we try to read a character from an empty file inLine 9
, an error occurs, and theerrno
flag is set. We use theclearerr
function to clear the error inLine 13
and continue normal operation.
Once the error is cleared, we can write to file in
Line 15
and attempt to reread a character inLine 19
. No errors occur this time.
#include <stdio.h> // inlcude relevant librariesint main () {FILE *filePointer;char c;filePointer = fopen("file.txt", "w"); // creating a new filec = fgetc(filePointer); // file is empty to an error will occurif( ferror(filePointer)) {printf("Error in reading from file : file.txt\n");}clearerr(filePointer); // clear error statusfprintf(filePointer, "Writing to file"); // writing to filefclose(filePointer);filePointer = fopen("file.txt", "r"); // open file with read modec = fgetc(filePointer); // no error should occur now// normal operation continuesprintf("Character is %c", c);fclose(filePointer);return(0);}
Free Resources