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 Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply