SOURCE CODE:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.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;
}
};
void main()
{
clrscr();
INVENTORY item;
fstream inoutfile;
inoutfile.open("STOCK.DAT",ios::ate|ios::in|ios::out|ios::binary);
inoutfile.seekg(0,ios::beg);
cout<<"CURRENT CONTENTS OF STOCK\n";
while(inoutfile.read((char*)&item,sizeof item))
{
item.putdata();
}
inoutfile.clear();
cout<<"\nADD AN ITEM\n";
item.getdata();
char ch;
cin.get(ch);
inoutfile.write((char *)&item,sizeof item);
inoutfile.seekg(0);
cout<<"CONTENTS OF APPENDED FILE\n";
while(inoutfile.read((char *)&item,sizeof item))
{
item.putdata();
}
int last=inoutfile.tellg();
int n=last/sizeof(item);
cout<<"Number of objects = "<<n<<"\n";
cout<<"Total bytes in the file = "<<last<<"\n";
cout<<"Enter object number to be updated : ";
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 the object\n";
item.getdata();
cin.get(ch);
inoutfile.write((char *)&item,sizeof item)<<flush;
inoutfile.seekg(0);
cout<<"CONTENTS OF UPDATED FILE\n";
while(inoutfile.read((char *)&item,sizeof item))
{
item.putdata();
}
inoutfile.close();
getch();
}
OUTPUT:
CURRENT CONTENTS OF STOCK
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
ADD AN ITEM
Enter name:YY
Enter code:10
Enter cost:101
CONTENTS OF APPENDED FILE
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
YY 10 101
Number of objects = 6
Total bytes in the file = 96
Enter object number to be updated : 6
Enter new values of the object
Enter name:ZZ
Enter code:20
Enter cost:201
CONTENTS OF UPDATED FILE
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
YY 10 101
ZZ 20 201
EmoticonEmoticon