C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Operator Overloading  >  Querying a File
 

Querying a File

The seekg() and tellg() functions can also be used for querying. A query can be based on the record number. For example, if the user wishes to see the 10th record,
ifstream ifile(“bill.dat”);
ifile.seekg(9 * sizeof(bill),ios:beg);

would position the record pointer at the beginning of the 10th record.

Program 20.2 is used to display any record from the file depending on the record number.



void query(void)
{
int num;
bill billobj;
ifstream ifile(“billfile.dat”);
ifile.seekg(0,ios::end);
int endpos = ifile.tellg();
int n = endpos/sizeof(bill);
cout<<”\n RECORD QUERY”;
cout<<”Which record do you want to query?”;
cout<<”Enter the record number”;
cin>>num;
int seekpos = (num-1) * sizeof(bill);
ifile.seekg(seekpos);
ifile.read((char *)&billobi.sizeof(bill));
cout<<\n The record is”;
billobj.showdata();
}



Similarly, a query can be based on the bill number. Program 20.3 is used to display a record based on the bill number entered by the user.

#include<fstream.h>
#include<iostream.h>
class bill
{
private:
int iBill_no;
float fBill_amt;
public:
void getdata()
{
..
}
void showdata()
{
..
}
void query(void)
{
int num;
bill billobj;
ifstream ifile(“billfile.dat”);
ifile.seekg(0,ios::end);
int endpos = ifile.tellg();
int n = endpos/sizeof(bill);
cout<<”RECORD QUERY \n”<<endl;
cout<<”Enter the record number you want to query”;
cin>>num;
int seekpos = (num-1) * sizeof(bill);
ifile.seekg(seekpos);
ifile.read((char *)&billobj, sizeof(bill));
cout<<”The record is :\n”;
billobj.showdata();
}
};
void main()
{
bill bobj;
bobj.query();
}

 

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright © 2008 - 3008  CppTutor.com All rights reserved.