can someone please show a example of how i can delete a record completely. thanks
Code:
#include<iostream>
#include<iomanip>
#include<fstream>
#include <cstring>
using namespace std;
struct hardware
{
char flag[1];
int record;
char name[100];
int quantity;
float cost;
};
void editrec(char *fname, int record, char *newname)
{
long int pos;
int count=0;
hardware temp = {0};
fstream file, outfile;
file.open(fname, ios::in | ios::out | ios::binary );
file.seekg(0,ios::beg);
file.read((char *)&temp, sizeof(hardware));
while (!file.eof())
{
if (temp.record == record)
{
strcpy(temp.name, newname);
pos=count*sizeof(temp);
file.seekp(pos,ios::beg);
file.write((char*)&temp,sizeof(hardware));
file.close();
break;
}
count++;
file.read( (char *)&temp, sizeof(hardware) );
}
}
void deleterec(char *fname, int record)
{
long int pos;
int count=0;
hardware temp = {0};
fstream file, outfile;
file.open(fname, ios::in | ios::out | ios::binary );
file.seekg(0,ios::beg);
file.read( (char *)&temp, sizeof(hardware) );
while ( !file.eof() )
{
if (temp.record == record)
{
temp.flag[0]='*';
pos=count*sizeof(temp);
file.seekp(pos,ios::beg);
file.write((char*)&temp,sizeof(hardware));
break;
}
count++;
file.read( (char *)&temp, sizeof(hardware) );
}
outfile.open("Temp.bin",ios::out | ios::binary);
file.seekg(0,ios::beg);
while(file.read((char*)&temp,sizeof(temp)))
{
if(temp.flag[0]!='*')
outfile.write((char*)&temp,sizeof(temp));
}
outfile.close();
file.close();
remove(fname);
rename("temp.bin",fname);
remove("temp.bin");
}
void get_data(char *fname)
{
string dummy;
int j;
hardware pwkr = {0};
fstream update_file(fname,ios::out|ios::binary|ios::app);
for(j = 0; j < 20; j++) pwkr.name[j] = ' '; // set array to spaces
cout << "Record #: ";
cin >> pwkr.record;
//Get rid of the newline inserted by the environment
cin.ignore(1,'n');
cout << "Tool Name: ";
cin.getline( pwkr.name, sizeof(pwkr.name) );
cout << "Quantity: ";
cin >> pwkr.quantity;
cout << "Cost: ";
cin >> pwkr.cost;
update_file.write(reinterpret_cast<char *>(&pwkr),sizeof(hardware));
update_file.close();
}
void show_hardware(char *fname)
{
int i = 0;
hardware temp = {0};
fstream show_file(fname,ios::binary|ios::in);
cout << "\n\nThese are the Hardware Tools in the System\n"
<< setiosflags(ios::showpoint | ios::fixed);
cout << "Tool\tRecord# Tool Name\tQuantity\tCost";
show_file.seekg(0,ios::beg);
show_file.read( (char *)&temp, sizeof(hardware) );
while ( !show_file.eof() )
{
i++;
cout << "\n" << i << "\t"
<< temp.record << "\t"
<< temp.name << "\t\t"
<< temp.quantity << "\t\t "
<< setprecision(2)
<< temp.cost;
show_file.read( (char *)&temp, sizeof(hardware) );
}
show_file.close();
}
int main(void)
{
get_data("empfile.bin");
show_hardware("empfile.bin");
editrec("empfile.bin", 1, "Dewalt");
show_hardware("empfile.bin");
deleterec("empfile.bin", 1);
show_hardware("empfile.bin");
return 0;
}