1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdio>
using namespace std;
struct Store{
int record;
char name[20];
int quantity;
double cost;
};
int main()
{
int r;
int choice;
//--------------Create 100 blank record into a file--------------
fstream fout("hardware.dat",ios::out|ios::binary);
Store blankstore={0,"",0,0.0};
for(int i=0;i<100;i++)
{
fout.write(reinterpret_cast<const char*>(&blankstore),sizeof(Store));
}
//---------------------add record into a file------------------------
ofstream outstore("hardware.dat",ios::out|ios::binary);
while(true)
{
cout<<"Enter record number.(0 to exit)\n?";
cin>>r;
while(r>100)
{
cout<<"The record number should be less than 100\nEnter again: ";
cin>>r;
}
if(r<=0)
{break;}
Store store;
store.record=r;
cout<<"Enter name of tool, quantity and cost.\n?";
cin>>store.name>>store.quantity>>store.cost;
outstore.seekp((store.record-1)*sizeof(Store));
outstore.write(reinterpret_cast<const char*>(&store),sizeof(Store));
}
outstore.close();
//-----------------Ask for choice----------------------------
cout<<"Enter choice: ";
cin>>choice;
while(choice>0 && choice<5)
{
if(choice ==1)//-----------print out all records form the file-----------------
{
ifstream instore("hardware.dat",ios::in|ios::binary);
cout<<left<<setw(10)<<"Record#"<<setw(12)<<"Tool name"<<setw(10)<<"Quantity"<<"Cost\n";
Store store;
instore.read(reinterpret_cast<char *>(&store),sizeof(Store));
while(instore&&!instore.eof())
{
if(store.record!=0)
cout<<left<<setw(10)<<store.record<<setw(12)<<store.name<<setw(10)
<<store.quantity<<store.cost<<endl;
instore.read(reinterpret_cast<char *>(&store),sizeof(Store));
}
instore.close();
}
else if(choice== 2)//------------ask for one record to be deleted---------
{
fstream delstore("hardware.dat",ios::out|ios::binary);
cout<<"Enter the record number: ";
cin>>r;
delstore.seekg((r-1)*sizeof(Store));
Store store;
delstore.read(reinterpret_cast<char *>(&store),sizeof(Store));
if(store.record!=0)
{
Store blankStore;
delstore.seekp((r-1)*sizeof(Store));
delstore.write(reinterpret_cast<const char*>(&blankStore),sizeof(Store));
cout<<"Record deleted!\n";
}
delstore.close();
}
//----------------------------------------------
cout<<"Enter choice: ";
cin>>choice;
}//---------------end fo while-----------
system("pause");
return 0;
}
|