C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

Record I/O (fwrite(), fread())

1. fread()

The fread() function reads the entire record( array or structure ) at a time from file.

Syntax:

fread( & structure variable, size of (structure variable), no of records, file pointer);

Example:

struct Student
   int sno;
   char sname [30];
   float mark;
} s;
FILE *fp;
fread (&s, sizeof (s), 1, fp);

2. fwrite()

The fwrite() function writes the entire record( array or structure ) at a time to the  file.

Syntax:

fread( & structure variable, size of (structure variable), no of records, file pointer);

Example:(for both fread() and fwrite())

Create a structure named Employee that has name,address and salary as member . Assume appropriate types and size of members. Use this structure to read and display records of 3 Employees. Write an array of structure to a file and then read its content to display to the screen.[structure, fread() ,fwrite()]

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	struct Employee
	{
		char name[20];
		int age;
		float salary;
	}e[3];
	int i;
	FILE *fptr;
	fptr=fopen("employee.txt","w+");
	if(fptr==NULL)
	{
		printf("file cannot be open");
		exit(1);
	}
	for(i=0;i<3;i++)
	{
		printf("name\t age\t salary");
		scanf("%s%d%f",e[i].name,&e[i].age,&e[i].salary);
	}
	printf("writing information to file\n");
	fwrite(&e,sizeof(e),3,fptr);
	fflush(stdin);
	rewind(fptr);
	printf("reading the content from file\n");
	fread(&e,sizeof(e),3,fptr);
	printf("students information is");
	for(i=0;i<3;i++)
	{
		printf("%s\t%d\t%f",e[i].name,e[i].age,e[i].salary);
	}
	fclose(fptr);
}