Home » Programming Languages » C Programs » feof() end-of-file indicator function in C – Example

feof() end-of-file indicator function in C – Example

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().

In below program, we read the file myfile.txt till the end of file has been detected and count the number of bytes. This can help us to measure the file length programatically.

#include <stdio.h>
#include <stdlib.h>

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

	if( (stream = fopen( "myfile.txt", "r" )) == NULL ) {
		printf("file not found\n");
		exit( 1 );
	}

	/* Cycle until end of file reached: */
	while( !feof( stream ) ) {

		/* Attempt to read in 10 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 );
}

compile this code as,

$ gcc -o feof feof.c

Make sure myfile.txt file is present of same directory as executable and Run the executable as,

$ ./feof 
Number of bytes read = 581

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

Leave a Comment