A program to enter the Roll No., Name and Marks obtained by different students in a Binary File, where the number of students whose data is to be stored is entered by the user.

 

#include<fstream.h>
#include<conio.h>
#include<stdio.h>

struct student
{
int rollno;
char name[23];
float marks;
};

void main()
{
clrscr();
student s[100];
int n,i;
cout<<"Enter the number of records to be stored: ";
cin>>n;
cout<<endl;

ofstream wfile;
wfile.open("student.dat");

for(int i=0;i<n;i++)
{
cout<<"Enter the roll number of the student "<<i+1<<": ";
cin>>s[i].rollno;
cout<<"Enter the name of the student "<<i+1<<": ";
gets(s[i].name);
cout<<"Enter the marks obtained by student "<<i+1<<": ";
cin>>s[i].marks;
cout<<endl;
}

for(i=0;i<n;i++)
wfile.write((char *)&s[i], sizeof(s[i]));
wfile.close();

ifstream yfile;
yfile.open("student.dat");

for(i=0;i<n;i++)
yfile.read((char *)&s[i],sizeof(s[i]));

while(yfile)
{
for(i=0;i<n;i++)
{
yfile.read((char *)&s[i],sizeof(s[i]));
cout<<"\n********************************************\n\n";
cout<<"Name: "<<s[i].name<<endl;
cout<<"Roll no.: "<<s[i].rollno<<endl;
cout<<"Marks: "<<s[i].marks<<endl;
}
}
cout<<"\n********************************************\n\n";

yfile.close();

getch();
}

 

< Back