Easy Tutorial
❮ C Exercise Example94 C Exercise Example36 ❯

C Library Function - clearerr()

C Standard Library - <stdio.h>

Description

The C library function void clearerr(FILE *stream) clears the end-of-file and error indicators for the given stream.

Declaration

Here is the declaration for the clearerr() function.

void clearerr(FILE *stream)

Parameters

Return Value

This function does not fail and does not set the external variable errno. However, if it detects that its argument is not a valid stream, it returns -1 and sets errno to EBADF.

Example

The following example demonstrates the use of the clearerr() function.

#include <stdio.h>

int main()
{
   FILE *fp;
   char c;

   fp = fopen("file.txt", "w");

   c = fgetc(fp);
   if( ferror(fp) )
   {
      printf("Error reading file: file.txt\n");
   }
   clearerr(fp);
   if( ferror(fp) )
   {
      printf("Error reading file: file.txt\n");
   }
   fclose(fp);

   return(0);
}

Assuming we have a text file file.txt, which is an empty file. Let's compile and run the above program, as we are trying to read a file opened in write-only mode, this will produce the following result.

Error reading file: file.txt

C Standard Library - <stdio.h>

❮ C Exercise Example94 C Exercise Example36 ❯