A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_clearerr.htm below:

C Library - clearerr() function

C Library - clearerr() function

The C library clearerr(FILE *stream) function clears the end-of-file and error indicators for the given stream. This can be useful when you want to reset the state of a file stream after an error or EOF condition has occurred.

Syntax

Following is the C library syntax of the clearerr() function −

void clearerr(FILE *stream);
Parameters

This function accepts only a single parameter −

Return Value

The clearerr function does not return a value. It is a void function, meaning it performs its operation without providing direct feedback.

Example 1 : Clearing EOF Flag

This example reads the contents of a file until EOF is reached, then clears the EOF flag using clearerr, and confirms that the EOF flag has been cleared.

Below is the illustration of C library clearerr(FILE *stream) function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   char ch;
   while ((ch = fgetc(file)) != EOF) {
       putchar(ch);
   }

   if (feof(file)) {
       printf("\nEOF reached.\n");
   }

   clearerr(file); // Clear the EOF flag

   if (feof(file)) {
       printf("EOF still set.\n");
   } else {
       printf("EOF cleared.\n");
   }

   fclose(file);
   return 0;
}
Output

The above code produces following result−

<contents of example.txt>
EOF reached.
EOF cleared.
Example 2: Resetting Stream State for Re-reading

This example reads the contents of a file until EOF is reached, clears the EOF flag with clearerr, rewinds the file to the beginning, and re-reads the file content to show that the stream state has been successfully reset.

#include <stdio.h>

int main() {
   FILE *file = fopen("example.txt", "r");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   char ch;
   while ((ch = fgetc(file)) != EOF) {
       putchar(ch);
   }

   if (feof(file)) {
       printf("\nEOF reached.\n");
   }

   clearerr(file); // Clear the EOF flag
   rewind(file);   // Reset file position to the beginning

   printf("Re-reading the file:\n");
   while ((ch = fgetc(file)) != EOF) {
       putchar(ch);
   }

   fclose(file);
   return 0;
}
Output

After execution of above code, we get the following result

<contents of example.txt>
EOF reached.
Re-reading the file:
<contents of example.txt>

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4