Write a program that performs Random Access any data file. The updating would include one or more of the following tasks: a) Displaying the contents of a file b) Modifying an existing item c) Adding a new item d ) Deleting an existing item
Write a program that performs Random Access any data file. The updating would include one or more of the following tasks: a) Displaying the contents of a file b) Modifying an existing item c) Adding a new item d ) Deleting an existing item
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#include<conio.h>
class INVENTORY
{
char name[10];
int code;
float cost;
public:
void getdata(void)
{
cout<<"Enter name : "; cin>>name;
cout<<"Enter code : "; cin>>code;
cout<<"Enter cost : "; cin>>cost;
}
void putdata(void)
{
cout<<setw(10)<<name
<<setw(10)<<code
<<setprecision(2)<<setw(10)<<cost
<<endl;
}
}; // end of class definition
int main()
{
clrscr();
INVENTORY item;
fstream inoutfile; // input/output stream
inoutfile.open("STOCK.DAT",ios::ate|ios::in|ios::out|ios::binary);
inoutfile.seekg(0,ios::beg); // go to start
cout<<"CURRENT CONTENTS OF STOCK\n";
while(inoutfile.read((char *) & item, sizeof (item)))
{
item.putdata();
}
inoutfile.clear(); // turn of EOF flag
/* >>>>>>>>>>>>>>>>> Add one or more item <<<<<<<<<<<<<<<<<< */
cout<<"\nADD AN ITEM\n";
item.getdata();
char ch;
cin.get(ch);
inoutfile.write((char *) & item, sizeof(item));
// display the appened file
inoutfile.seekg(0); // go to start
cout<<"CONTENTS OF APPEND FILE\n";
while(inoutfile.read((char *) & item, sizeof (item)))
{
item.putdata();
}
// find number of objects in the file
int last = inoutfile.tellg();
int n = last/sizeof(item);
cout<<"Number of objects = "<<n<<"\n";
cout<<"Total bytes in the file = "<<last<<"\n";
/* >>>>>>>> MODIFY THE DETAILS OF AN ITEM <<<<<<<<<<<<<<< */
cout<<"Enter object number to be updated\n";
int object;
cin>>object;
cin.get(ch);
int location = (object-1) * sizeof(item);
if(inoutfile.eof())
inoutfile.clear();
inoutfile.seekp(location);
cout<<"Enter new values of th object\n";
item.getdata();
cin.get(ch);
inoutfile.write((char *) & item, sizeof (item))<<flush;
/* >>>>>>>>>>>>>> SHOW UPDATED FILE <<<<<<<<<<<<<<<<<< */
inoutfile.seekg(0); // go to the start
cout<<"CONTENTS OF UPDATED FILE\n";
while(inoutfile.read((char *) & item, sizeof (item)))
{
item.putdata();
}
inoutfile.close();
return 0;
} // end of main