C programming ferror stdio.h


In C programming the <stdio.h> ferror function tests the error indicator for the stream.The declaration of the function is given below.

int ferror(FILE *stream);

Parameters:
stream -The pointer to the file whose error is to be checked.

Return type
int -Returns nonzero if and only if the error indicator is set for stream.

A code example is given below.

Code example

FILE *fp=fopen(“text.cpp” , “rb+”);
int val , count ;

if (fp != NULL)
{
while ( (val=fgetc(fp)) !=EOF) //read text.bin file
{
if( ferror(fp) ) //test if there is any error while reading from the file
{
fprintf(stderr , “\nAn error occurred”);
break;
}
printf(“%c” , val);
}
else
printf(“File cannot be opened”);

fclose( fp );

If there is any error while reading character from the file the program will print “An error has occurred”.


Related links

->C clearerr

->C perror

->C feof

->C fgetc