Write a program using fread( ) and fwrite( ) to create a file of records and then read and print the same file.
Answers
The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a structure.
Syntax of fwrite() function
fwrite( ptr, int size, int n, FILE *fp );
The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.
Example of fwrite() function
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct Student Stu;
fp = fopen("Student.dat","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);
printf("Enter Name : ");
scanf("%s",Stu.name);
printf("Enter Marks : ");
scanf("%f",&Stu.marks);
fwrite(&Stu,sizeof(Stu),1,fp);
printf("\nDo you want to add another data (y/n) : ");
ch = getche();
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
fclose(fp);
}
Output :
Enter Roll : 1
Enter Name : Ashish
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : Kaushal
Enter Marks : 72.65
Do you want to add another data (y/n) : y
Enter Roll : 3
Enter Name : Vishwas
Enter Marks : 82.65
Do you want to add another data (y/n) : n
Data written successfully...
The fread() function
The fread() function is used to read bytes form the file.
Syntax of fread() function
fread( ptr, int size, int n, FILE *fp );
The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where data will be stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
FILE* : FILE* is a file where the records will be read.
Example of fread() function
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct Student Stu;
fp = fopen("Student.dat","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
printf("\n\tRoll\tName\tMarks\n");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t%f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);
}
Output :
Roll Name Marks
1 Ashish 78.53
2 Kaushal 72.65
3 Vishwas 82.65