You are here:

C++/C++ File Stream

Advertisement


Question
i have created a file in c++ for the library system. now i wanted to search the records by ID wise. how can i do it. could u plz help me with appropriate example.


Answer
i think this would clear your doubt


struct library_books
 {
    int id;
     char[80] name;
}lib;
main()
{
int i,count;
cout<<"Enter the num of records";
cin>>i;

// Enter the details
for(count=1;count<=i;count++)
{
cin>>"record id ">>lib.i>>"name">>lib.name;
}

//open a file librarysystem and copy the data into it
ofstream outf("librarysystem",ios::out|ios::binary);
if(!outf)
cout<<"sorry the file couldn't be opened for output";
outf.write(*(&char)lib,sizeof(struct lib));

// to search for record usind id first read the contents of the file
ifstream inf("librarysystem",ios::in|ios::binary);
if(!inf)
cout<<"sorry the file couldn't be opened for input";
inf.read((*(&char)lib,sizeof(struct lib));

//search begins now
cout<<"Enter the record id to be searched";
cin>>id;
while(count != i)
{
if(id == lib.id)
{
cout<<"rec present and the details are";
cout<<"ID:"<<lib.id<<"Name"<<lib.name;
}
else
{
cout<<"sorry record not found"<<;
break;
}
}
Does this clear your doubt?  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Saikrishna

Expertise

I can answer questions in C (Basic and a little of advanced). I can't answer questions related to multi threading

Experience

2.6 years

Education/Credentials
I am a B-tech graduate majored in computer science.

©2016 About.com. All rights reserved.