What are Stream Error Functions in C Language?

Question: What are Stream Error Functions in C Language?

Answer: We have functions in ANSI C specification which are used to determine the state of a stream. These are prototyped below,

    int feof(FILE *stream);
    int ferror(FILE *stream);
    void clearerr(FILE *stream);

‘feof()’ returns TRUE if stream is currently at end of file. Well! We have already seen that we can change current position in the file using fseek(), rewind() or fsetpos() functions. For ex.

To set to the beginning in a given stream,

    stream = fopen("file", "r");
    rewind(stream);

or we can use

advertisement
advertisement
    fseek(stream, 0, SEEK_SET);

‘ferror()’ reports on error state of stream and returns TRUE if any read/write errors have occurred.

Note: Join free Sanfoundry classes at Telegram or Youtube
/* ferror.c */
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
 
int main(void)
{
    FILE *stream;
    char buffer[SIZE];
 
    stream = fopen("hello.txt", "r");
    if (stream == NULL) {
        perror("File Open");
        exit(EXIT_FAILURE);
    }
 
    /* read from the stream into buffer */
    fgets(buffer, SIZE, stream);
 
    /* check if there were any read/erite errors */
    if (ferror(stream))
        printf("Read/ Write Error.\n");
 
    return 0;
}

Finally, ‘clearerr()’ resets error indication on a given stream.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.