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_ferror.htm below:

C Library - ferror() function

C Library - ferror() function

The C library ferror(FILE *stream) function tests the error indicator for the given stream.When working with file operations, it is important to be aware of any errors that may occur, as they can lead to corrupted data, crashes, or undefined behavior. The ferror function helps in detecting such errors.

Syntax

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

int ferror(FILE *stream);
Parameter Return Value

The ferror function returns a non-zero value if an error has occurred with the specified stream.It returns 0 if no error has occurred.

Example 1: Checking for Errors after Writing to a File

This example attempts to write some text to a file. After writing, it checks if any error occurred using ferror.

Below is the illustration of C library ferror() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   fputs("Hello, World!", file);

   if (ferror(file)) {
       printf("An error occurred while writing to the file.\n");
   } else {
       printf("Writing to the file was successful.\n");
   }

   fclose(file);
   return 0;
}
Output

The above code produces following result−

Writing to the file was successful.
Example 2: Forcing an Error by Closing a File Prematurely

In this example we force an error by closing the file and then attempting to write to it. It checks for the error using ferror.

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   fputs("This is a test.", file);

   fclose(file);

   // Attempt to write to the closed file
   fputs("This will cause an error.", file);

   if (ferror(file)) {
       printf("An error occurred because the file was already closed.\n");
   } else {
       printf("Writing to the file was successful.\n");
   }

   return 0;
}
Output

After execution of above code, we get the following result

An error occurred because the file was already closed.

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