In this post we will write a C++ program to update the record in binary mode.
C++ program to update the record in binary mode
#include<iostream>
#include<conio.h>
#include<fstream>
#include<process.h>
using namespace std;
class rec
{
protected:
int roll;
int long phon;
char name[20];
public:
input()
{
std::cout<<"Enter the name = ";
std::cin>>name;
std::cout<<"Enter the roll # = ";
std::cin>>roll;
std::cout<<"Enter the phone # = ";
std::cin>>phon;
}
dis()
{
std::cout<<name<<"t"<<roll<<"t"<<phon<<std::endl;
}
};
int main()
{
system("cls");
int recn,n;
rec r;
fstream fir("new.cpp",ios::binary|ios::in|ios::out);
if(!fir)
{
std::cout<<"File opening error"<<std::endl;
getch();
exit(0);
}
fir.seekg(0,ios::end);
int endp = fir.tellg();
n = endp/sizeof(r);
std::cout<<"Number of records in file = "<<n<<std::endl;
std::cout<<"Enter any key"<<std::endl;
getch();
std::cout<<"Enter record Number you want to update = ";
std::cin>>recn;
long int pos = (recn-1)*sizeof(r);
fir.seekg(pos);
std::cout<<"You are modify the record "<<std::endl;
fir.read((char*)&r, sizeof(r));
r.dis();
std::cout<<"Now enter new entry"<<std::endl;
fir.seekg(pos);
r.input();
fir.write((char*)&r, sizeof(r));
std::cout<<"Record has updated successfully";
getch();
return 0;
}
Output
Number of records in file = 2 Enter any key Enter record Number you want to update = 1 You are modify the record ABC 1 12345 Now enter new entry Enter the name = A Enter the roll # = 1 Enter the phone # = 12345 Record has updated successfully