I made this program for my school holiday homework. I made a program to enter records into a binary file and then search for existing record. The problem i am having is that it searches for the first record correctly but is unable to search the other records.
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
struct book
{char author[40];
int bid;
char bname[40];};
struct student
{book b;
char name[20];
int rno;
int admno;
char sec;
int cl;};
void getdata(student &);
void writefile();
void searchfile(student &,int);
void readfile();
student s1;
void main()
{clrscr();
char ch1='y';
int ch,id;
cout<<"\t\tAIR FORCE BAL BHARATI SCHOOL LIBRARY RECORDS";
cout<<"\n\n\n\t\t\t PRESS ANY KEY TO CONTINUE";
getch();
clrscr();
cout<<"\t\t PROGRAM TO MAINTAIN SCHOOL LIBRARY RECORDS \n\t\t\tMADE BY SOUMYA SAMANTA\n";
while ((ch1=='y')||(ch1=='Y'))
{cout<<"1)Write into a file\n2)Search for an issued book"<<endl;
cout<<"Enter your choice : ";
cin>>ch;
switch(ch)
{case 1:
writefile();
break;
case 2:
searchfile(s1,id);
break;
case 3:
default:
cout<<"\nPlease enter a valid choice";
break;}
cout<<"\nDo you want to continue (y/n) ? : ";
cin>>ch1;
cout<<"\n\n\n";}
getch();
}
void writefile()
{clrscr();
ofstream f1;
f1.open("library.dat",ios::app|ios::binary);
getdata(s1);
f1.write((char*)&s1,sizeof(student));
f1.close();}
void getdata(student &s)
{clrscr();
cout<<"Enter name : ";
gets(s.name);
cout<<"\nEnter roll no. : ";
cin>>s.rno;
cout<<"\nEnter admission number : ";
cin>>s.admno;
cout<<"\nEnter class : ";
cin>>s.cl;
cout<<"\nEnter section : ";
cin>>s.sec;
cout<<"\nEnter book ID number : ";
cin>>s.b.bid;
cout<<"\nName of author : ";
gets(s.b.author);
cout<<"\nName of book is : ";
gets(s.b.bname);
cout<<"\nYour details have been saved ";
cout<<"\nPress any key to continue ";
getch();
clrscr();}
void searchfile(student &s1,int id)
{clrscr();
cout<<"Enter book ID to be searched for : ";
cin>>id;
ifstream f1;
char f='n';
f1.open("library.dat",ios::in|ios::binary);
while (!f1.eof())
{f1.read((char*)&s1,sizeof(student));
if (id==s1.b.bid)
f='y';
break;}
if (f=='y')
readfile();
else
cout<<"\nMatch not found";}
void readfile()
{clrscr();
ifstream f2;
f2.open("library.dat",ios::in||ios::binary);
while (!f2.eof())
{f2.read((char*)&s1,sizeof(student));
cout<<"\n\t\t\tDetail of the searched book is \n";
cout<<"\nName of student : "<<s1.name;
cout<<"\nAdmission number is : "<<s1.admno;
cout<<"\nRoll no. is : "<<s1.rno;
cout<<"\nClass is "<<s1.cl<<"-"<<s1.sec;
cout<<"\nName of book is : "<<s1.b.bname;
cout<<"\nName of author is : "<<s1.b.author;
cout<<"\nBook ID is : "<<s1.b.bid;
break;}
f2.close();}
Why do all your functions return void? Also, main must return an int, not void. For your Get functions wouldn't it make more sense to return the data rather than modifying outside data through a reference? And yes, please do indent. You may even be able to find a feature in your IDE or on the web to auto-indent the code for you.