Home » Programming Languages » C Programs » C program to read file contents and count bytes using feof API

C program to read file contents and count bytes using feof API

The function feof() tests the end-of-file indicator for the stream pointed to by stream, returning nonzero if it is set. The end-of-file indicator can be cleared only by the function clearerr().

 $ vim read_file_till_end_of_file_detected.c 
#include <stdlib.h>

int main(int argc, char **argv) {
        int  count, total = 0;
        char buffer[100];
        FILE *stream;

        if((stream = fopen(argv[1], "r" )) == NULL )
                exit( 1 );

        /* Iterate till end of file reached: */
        while(!feof(stream)) {
                /* Attempt to read in 100 bytes: */
                count = fread(buffer, sizeof( char ), 100, stream);
                if(ferror(stream)) {
                        perror("Read error");
                        break;
                }

                /* Total up actual bytes read */
                total += count;
        }
        printf( "Number of bytes read = %d\n", total );
        fclose( stream );
        return 0;
}
 $ gcc -o read_file_till_end_of_file_detected read_file_till_end_of_file_detected.c 

Below command, reads read_file_till_end_of_file_detected.c till end of file is detected and counts the number of bytes and prints on console.

$ ./read_file_till_end_of_file_detected  read_file_till_end_of_file_detected.c 
Number of bytes read = 550

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment