In this post we will write a C++ program to search the record in binary file.
C++ program to search the record in binary file.
#include<iostream>
#include<conio.h>
#include<fstream>
#include<process.h>
#include<string.h>
#include<iomanip>
#include<stdio.h>
using namespace std;
class rec
{
private:
char name[100];
public:
char roll[100];
void input()
{
std::cout<<"Enter the full name = ";
gets(name);
std::cout<<"Enter the roll = ";
gets(roll);
}
void dis()
{
system("cls");
puts(name);
puts(roll);
}
};
int main()
{
char froll[100];
int t = 0;
long int rn = 0;
char ch = 'y';
rec r;
system("cls");
ofstream fir("abc.rec",ios::binary);
if(!fir)
{
cerr<<"File opening error";
getch();
exit(0);
}
std::cout<<"Enter the names in file"<<std::endl;
while(ch != 'n')
{
r.input();
fir.write((char *)&r, sizeof(r));
std::cout<<"Do you want to enter new record (Y/N) = ";
std::cin>>ch;
}
fir.close();
ifstream sec("abc.rec",ios::binary);
if(!sec)
{
cerr<<"File opening error";
getch();
exit(0);
}
std::cout<<std::endl;
std::cout<<"Enter the roll number = ";
std::cin>>froll;
while(sec.read((char*)&r, sizeof(r)))
{
if(strcmp(froll,r.roll) == 0)
{
rn = (rn-1)*sizeof(r);
sec.seekg(rn);
r.dis();
sec.close();
t = 1;
}
rn++;
}
if(t==0)
std::cout<<"Name does not exist";
getch();
}
Output
Enter the names in file Enter the full name = ABC Enter the roll = 1 Do you want to enter new record (Y/N) = y Enter the full name = XYZ Enter the roll = 2 Do you want to enter new record (Y/N) = n Enter the roll number = 2 XYZ 2