CPP program to Edit a record in Binary file

Modify a record in 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;
char* retname(){ return (name); }
};

C++ program to modify 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){
s.read_data() ;  // this way we are overwriting the current record’s entries
}
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 able to modify a record from a binary file.

Author: rakesh kumar

cbsetoday.com is my online home, here I share all the information related to education, programming - and everything else that attract me. You can get in touch with me in these social sharing websites
Download File :

Leave a Reply