C Programming language

Record I/O : What is Block Read/Write, How to use fwrite( ) Function in C
Previous Home Next

Record I/O

It is useful to store block of data into file rather than individual elements . Each block has some fixed size, it may be structure and array. It is easy to to read the entire block from a file or write a entire block to the file.

There are to useful function for this purpose.

  1. fwrite ( ) Function
  2. fread ( ) Function

Although we can read and write any type of data varying from a single character to array through these function, these function are mainly used for binary files or binary modes. ( wb, rb )

fwrite () Function

fwrite function writes a block of data to the given file.

size_t fwrite (const void *ptr, size_t size, size_t count, FILE *stream) ;

size_t is defined in stdio.h .void means that it is a pointer that can be used for any type variable. ptr is points to the block of memory that contains the information to be written to the file ,size denotes the length of each items in bytes

n is the number of items to be written to the file . fptr is a file pointer which points to the file to which the data is written .if successful , fwrite will return n items.on error it will return a number less then n

#include <stdio.h>
struct emp
{
	char name[40] ;
	int age ;
	float sal ;
}
employee ;
fwrite(&employee,sizeof(employee),1,fp);

This will write single structure to the file.

/** Receives records from keyboard and writes them to a file in binary mode*/
#include<stdio.h>
main( )
{
	FILE *fp ;
	char another = 'Y' ;
	struct emp
	{
		char name[40] ;
		int age ;
		float sal ;
	} ;
	struct emp e ;
	fp = fopen ( "EMP.DAT", "wb" ) ;
	if ( fp == NULL )
	{
		puts ( "Cannot open file" ) ;
		exit( ) ;
	}
	while ( another == 'Y' )
	{
		printf ( "\nEnter name, age and basic salary: " ) ;
		scanf ( "%s %d %f", e.name, &e.age, &e.sal ) ;
		fwrite ( &e, sizeof ( e ), 1, fp ) ;
		printf ( "Add another record (Y/N) " ) ;
		Chapter 12: File Input/Output 439
		fflush ( stdin ) ;
		another = getche( ) ;
	}
	fclose ( fp ) ;
};
Previous Home Next