I have the following class declaration:
class student
{
int roll,marks;
public:
void input()
{
cout<<"Roll:";cin>>roll;
cout<<"Marks:";cin>>marks;
}
void display()
{
cout<<"Roll:"<<roll<<endl;
cout<<"Marks:"<<marks<<endl;
}
int retroll()
{
return roll;
}
};
I am storing 3 records of the type student in a binary file
void writerec()
{
student a;
ofstream fout ("student.dat",ios::binary);
for (int x = 1 ; x<=3 ; x++)
{
a.input();
fout.write((char*)&a,sizeof(a));
}
}
This is my function to read the records from the file
void readrec()
{
student a;
ifstream fin ("student.dat",ios::binary);
for (int x = 1 ; x<=3 ; x++)
{
fin.read((char*)&a,sizeof(a));
a.display();
}
}
Here is my function to delete the records from the file
void deleterec(int r) //takes roll number that needs to be deleted
{
student a;
ofstream fout ("temp.dat",ios::binary);
ifstream fin ("student.dat",ios::binary);
while(fin.read((char*)&a,sizeof(a)))
if(a.retroll()!=r)
fout.write((char*)&a,sizeof(a));
fin.close();
fout.close();
remove("student.dat");
rename("temp.dat","student.dat");
}
Here is my main function:
void main()
{
student a;
writerec();
deleterec(2);
cout<<"Record Deleted\n";
readrec();
}
So I am deleting all the records with roll number 2.
Here is my sample input:
Roll:2
Marks:20
Roll:2
Marks:20
Roll:2
Marks:20
Here is my output:
Record Deleted
Roll:0
Marks:1
Roll:0
Marks:1
Roll:0
Marks:1
So my question is after deleting the 3 records with roll number 2 , how does the binary file still retain values . Also how come the value of marks is 1?
Thanks for the help :)
There is a problem in your readrec() function
You are forcefully reading three records from a file (even if they dont exist)
So, a.display() displays the initial values of variables (since nothing can be read from an empty file)
I think you need to modify readrec() as :
while(fin.read((char*)&a,sizeof(a)))
a.display();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With