Easy Tutorial
❮ C Function Memcmp C Examples Lcm ❯

C Library Function - ferror()

C Standard Library - <stdio.h>

Description

The C library function int ferror(FILE *stream) tests the error indicator for the given stream.

Declaration

Here is the declaration for the ferror() function.

int ferror(FILE *stream)

Parameters

Return Value

The function returns a non-zero value if the error indicator associated with the stream is set, otherwise it returns a zero value.

Example

The following example demonstrates the use of the ferror() 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 attempt 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 Function Memcmp C Examples Lcm ❯