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");

                /* 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
Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question