C Programming language

Record I/O : How to use fread( ) Function in C
Previous Home Next

The fread() Function is a block oriented function and used to read a block of data from the file. It provide as much control as fgetc() in the program, and has the advantage of being able to read more than one character in a single I/O operation.

fread (ptr, size, n, fptr);

Here ptr is the address of data item (an array or a structure) where the block of data will be stored after reading, size is the size of the data item in bytes to be read, n is the number of data items and fptr is the file pointer of type FILE structure. The fread( ) function returns the number of full data items actually read, which may be less than ‘n’ (possibly 0) if function causes any error.

/* * program to understand the use of fread() */
void main( )
	FILE *fp ;
	struct emp
		char name[40] ;
		int age ;
		float bs ;
	} ;
	struct emp e ;
	fp = fopen ( "EMP.DAT", "rb" ) ;
	if ( fp == NULL )
		puts ( "Cannot open file" ) ;
		exit( ) ;[an error occurred while processing this directive]
	while ( fread ( &e, sizeof ( e ), 1, fp ) == 1 )
	printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;
	fclose ( fp ) ;
Previous Home Next