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.

advertisement

To set to the beginning in a given stream,

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

or we can use

advertisement
    fseek(stream, 0, SEEK_SET);

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

advertisement
/* 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.

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!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn