Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is clearerr in C?

Hassaan Waqar

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:

How does clearerr work?

Declaration

The clearerr function is defined as follows:

void clearerr(FILE *stream);

It takes a filestream as a parameter.

Return type

The function does not return anything. Hence, the return type is void.

Example

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 in Line 9, an error occurs, and the errno flag is set. We use the clearerr function to clear the error in Line 13 and continue normal operation.

Once the error is cleared, we can write to file in Line 15 and attempt to reread a character in Line 19. No errors occur this time.

#include <stdio.h> // inlcude relevant libraries

int main () {
  
  FILE *filePointer;
  char c;
  
  filePointer = fopen("file.txt", "w"); // creating a new file 
  c = fgetc(filePointer); // file is empty to an error will occur
  if( ferror(filePointer)) {
    printf("Error in reading from file : file.txt\n");
  }
  clearerr(filePointer); // clear error status

  fprintf(filePointer, "Writing to file"); // writing to file
  fclose(filePointer);

  filePointer = fopen("file.txt", "r"); // open file with read mode
  c = fgetc(filePointer); // no error should occur now
  // normal operation continues
  printf("Character is %c", c); 
  fclose(filePointer);
   return(0);
}

RELATED TAGS

c

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring