#include <iostream.h>
#include <fstream.h>
struct contact
{
char name[10];
int age;
};
struct address
{
char city[10];
char country[10];
};
class DtbRec
{
private:
contact cnt;
address adr;
public:
void getdata();
void dispdata();
};
/*
I will give you a bit of work, make the funtions getdata() and dispdata()
It's easy and not worth for me to bother with now :-}
*/
void DtbRec::getdata() //get user input
{
cout <<"Enter info(Name,age,city,country)"<<endl;
cin>>cnt.name;
cin>>cnt.age;
cin>>adr.city;
cin>>adr.country;
}
void DtbRec::dispdata() //display to screen
{
cout<<cnt.name<<endl;
cout<<cnt.age<<endl;
cout<<adr.city<<endl;
cout<<adr.country<<endl;
}
//This program is not tested, have fun fixing errors, if any
//I am a taos programmer so dont expect anything major
//Typing mistakes are not errors
//This was done off the cuff and not even compiled once
int main()
{
DtbRec xRec; //temp rec
fstream fl_h; //file handle
char ch;
int num;
fl_h.open("database.txt",ios::in|ios::out|ios::binary|ios::trunc);
do
{
cout<<"\n\nFstream Dtb\n"
<<"\n1.Add records"
<<"\n2.View records"
<<"\n3.Modify records"
<<"\n4.Exit"
<<"\n\tEnter Choice:";
cin>>ch;
if(ch == '1') //we are dealing with chars not ints
{
//Adding a rec
fl_h.seekp(0,ios::end); //will disscuss this later,this sets the file write pointer to
//the end of a file.
xRec.getdata(); //Get some data from the user
fl_h.write((char*)&xRec,sizeof(DtbRec));
fl_h.seekg(0,ios::end);
num=fl_h.tellg();
int rec;
rec=num/(sizeof(DtbRec));
cout<<"No of recs="<<rec;
}
else if(ch == '2')
{
//View recs
fl_h.seekg(0,ios::beg); //will disscuss this later,this sets the file read pointer to the
//begining of a file.
int n = 0;
fl_h.seekg(0,ios::beg);
while(!fl_h.eof()) //will disscuss this later,it check if the file's end has been reached
{
n++;
fl_h.read((char*)&xRec,sizeof(DtbRec));
cout<<"\nRecord No["<<n<<"]\n";
xRec.dispdata(); //Show the user all the data present
}
}
else if(ch == '3')
{
//Modify me colors ;-)
cout<<"Enter the record no(starts at 0):";
cin>>num;
fl_h.seekg(num*sizeof(DtbRec),ios::beg); //move the read pointer to where the rec is
fl_h.read((char*)&xRec,sizeof(DtbRec)); //read it
xRec.dispdata(); //Show the info
xRec.getdata(); //Let the user change the info
fl_h.seekp(num*sizeof(DtbRec),ios::beg); //move the write ponter this time
fl_h.write((char*)&xRec,sizeof(DtbRec)); //overwrite with new info
//yahoo,modification done.I have seen too many people who just
//cant get modification .It's so simiple I just cant get why they just cant
//get it ;-)
}
}while(ch != '4');
fl_h.close(); //close the file
cout<<"\nEnd of Program";
return 0;
}