PGM14

You might also like

You are on page 1of 2

PROGRAM NO: 14

DATE:

/*Consider a binary file "Myfile.dat" and write a menu driven program to add,
read and display and delete records. The program should work as many times
as the user wants.*/
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<stdio.h>
void Store();
void Display();
void Delete();
struct student
{
char name[40];
int roll;
float mark;
};
student s;
void main()
{
clrscr();
char opt1;
int ch;
do
{
cout<<"\nMENU";
cout<<"\n1.Write details of students into a file";
cout<<"\n2.Display the contents of a file";
cout<<"\n3.Delete the details of a student whose roll number is specified by the
user";
cout<<"\n4.Exit";
cout<<"\nENTER CHOICE:";
cin>>ch;
if (ch==1)
Store();
else if (ch==2)
Display();
else if (ch==3)
Delete();
else if (ch==4)
exit(0);
else
cout<<"\nWrong Choice!";
cout<<"\nDo you want to continue?(Y/N):";
cin>>opt1;
}while(opt1=='Y'||opt1=='y');
getch();
}
void Store()
{
char opt2;
ofstream fout("Myfile.dat",ios::binary|ios::app);
do
{
cout<<"\nEnter name:";
gets(s.name);
cout<<"\nEnter roll number:";
cin>>s.roll;
cout<<"\nEnter marks:";
cin>>s.mark;
fout.write((char*)&s,sizeof(s));
cout<<"\nDo you want to enter details of another student?(Y/N):";
cin>>opt2;
}while(opt2=='Y'||opt2=='y');
fout.close();
}
void Display()
{
ifstream fin ("Myfile.dat",ios::binary);
while (fin.read((char*)&s,sizeof(s)))
{
cout<<"\nNAME:"<<s.name;
cout<<"\nROLL NUMBER:"<<s.roll;
cout<<"\nMARK:"<<s.mark;
}
fin.close();
}
void Delete()
{
int r;
cout<<"\nEnter the roll number of the student whose details has to be deleted:";
cin>>r;
ifstream fin("Myfile.dat",ios::binary);
ofstream fout("Temp.dat",ios::binary);
while (fin.read((char*)&s,sizeof(s)))
{
if (s.roll!=r)
fout.write((char*)&s,sizeof(s));
}
fin.close();
fout.close();
remove ("Myfile.dat");
rename("Temp.dat","Myfile.dat");
}

You might also like