CPP program to delete a record from a binary file
Delete a record from a binary file is one of the most useful operations on binary file but unfortunately, there is no direct command to do the needful. So we have to take help of a temporary file to remove a record from a binary file.
Here in this C++ program, we are assuming that a binary file “student.dat” already exists and contains some records of student class as mentioned below.
class student {
int roll,
char name[30];
char address [100];
public:
void read_data() ; // member function to read data from keyboard
void show_data() ; // member function to show data members on the screen;
};
C++ program to remove a particular record having name “rakesh kumar”
#include<iostream>
#include<fstream>
#include<stdio.h>
int main() {
ifstream fin(“student.dat”); // file open in reading mode
ofstream fout(“temp.dat”); // file open in writing mode
student s;
while(fin.read(char*)&s, sizeof(student))) {
{ if (strcmp(s.retname(),”rakesh kumar”)!=0)
fout.write((char*)&s,sizeof(student));
}
fin.close();
fout.close();
remove(“student.dat”);
rename(“temp.dat”,”student.dat”);
return 0;
}
The above progra,m opens “student.dat” binary file in reading mode and a secondary file in writing more. Read and check end of file using while loop, if the record does not contain our particulr name then it write the same record in tempray file “temp.dat” and repeat this process until end of file
Suggested Read :
Basic File operation in Binary file
Basic File operation on Text File
finally ,remove our original binary file as rename temporary file as othe riginal file name. Using this method we actully remove a record from a binary file.