Binary File Handling in CPP - Binary File Handling in C++ Examples
|
Binary File Handling in CPP - Binary File Handling in C++ Examples |
Soltuion:
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
class BOOK
{
int b_no;
char b_name[50];
public:
void getdetails()
{
cout<<"\n Enter book no.: ";
cin>>b_no;
cout<<"\n Enter book name: ";
gets(b_name);
}
void showdetails()
{
cout<<"\n Book no.: "<<b_no;
cout<<"\n Book name: ";
puts(b_name);
}
int return_b_no() {return b_no;}
};
void insert()
{
BOOK obj;
obj.getdetails();
ofstream ofile;
ofile.open("BOOK.DAT",ios::app|ios::binary);
ofile.write((char*)&obj,sizeof(obj));
ofile.close();
cout<<"\n Insert successful. Press any key to continue...";
getch();
}
void display()
{
BOOK obj;
ifstream ifile;
ifile.open("BOOK.DAT");
while(ifile.read((char*)&obj,sizeof(obj)))
{obj.showdetails();}
ifile.close();
cout<<"\n Press any key to continue...";
getch();
}
void search()
{
BOOK obj;
int b_no,token=0;
cout<<"\n Enter book no. to be searched: ";
cin>>b_no;
ifstream ifile;
ifile.open("BOOK.DAT");
while(ifile.read((char*)&obj,sizeof(obj)))
{
if(obj.return_b_no()==b_no)
{
cout<<"\n Record found!";
token=1;
obj.showdetails();
}
}
ifile.close();
if(token==0)
cout<<"\n Record not found.";
cout<<"\n Press any key to continue...";
getch();
}
void count()
{
BOOK obj;
int count=0;
ifstream ifile;
ifile.open("BOOK.DAT");
while(ifile.read((char*)&obj,sizeof(obj)))
count++;
ifile.close();
cout<<"\n Number of records in the file: "<<count;
cout<<"\n Press any key to continue...";
getch();
}
void modify()
{
BOOK obj;
int b_no,token=0;
int pos ;
cout<<"\n Enter book no. to be modified: ";
cin>>b_no;
fstream file;
file.open("BOOK.DAT",ios::binary|ios::in|ios::out);
while(file.read((char*)&obj,sizeof(obj)))
{
pos=-1*sizeof(obj) ;
if(obj.return_b_no()==b_no)
{
token=1;
obj.showdetails();
cout<<"\n Modify:\n";
file.seekg(pos,ios::cur);
obj.getdetails();
file.write((char*)&obj,sizeof(obj));
cout<<"\n Modify successful!";
}
}
if(token==0)
cout<<"\n Record not found.";
cout<<"\n Press any key to continue...";
file.close();
getch();
}
void main()
{
while(1)
{
clrscr();
cout<<"\n\t\tMain Menu:-";
cout<<"\n\n\t1.Insert";
cout<<"\n\t2.Dispay";
cout<<"\n\t3.Search";
cout<<"\n\t4.Count";
cout<<"\n\t5.Modify";
cout<<"\n\t6.Exit";
cout<<"\n\n\tEnter choice: ";
int choice;
cin>>choice;
switch(choice)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
count();
break;
case 5:
modify();
break;
case 6:
exit(0);
}
}
}
This Binary File Handling in C++ Examples.