Code:
void POS::deleteRecord(char fileName[], string itemNum)
{
// objects for writing and reading
ofstream write;
ifstream read;
counter = 0; // used for renumbering records after deletion
// variables for storing record details
string num, name, manu, type, reso, cost, pric, quan;
write.open("temp.txt", ios::out); // open temp file for storing valid records
write << ""; // empty file just in case.
read.open("Printers.txt"); // open file for reading
// read first record on file
getline(read, num);
getline(read, name);
getline(read, manu);
getline(read, type);
getline(read, reso);
getline(read, cost);
getline(read, pric);
getline(read, quan);
getline(read, readSpace); // store space as well
// read file until no more records exist
while(!read.fail())
{
if (itemNum.compare(num)== 0) // if record's num equals our search item
{
// delete record
num.erase(num.begin(), num.end()); // delete every character of record
name.erase(name.begin(), name.end());
manu.erase(manu.begin(),manu.end());
type.erase(type.begin(),type.end());
reso.erase(reso.begin(),reso.end());
cost.erase(cost.begin(),cost.end());
pric.erase(pric.begin(),pric.end());
quan.erase(quan.begin(),quan.end());
}// end if
else // else store only valid records (quantity > 0)
{
counter++; // new item counter
write << counter << endl // insert new item numbering
<< name << endl
<< manu << endl
<< type << endl
<< reso << endl
<< cost << endl
<< pric << endl
<< quan << endl
<< endl; // inserts a space between records
}// end else
// read another record
getline(read, num);
getline(read, name);
getline(read, manu);
getline(read, type);
getline(read, reso);
getline(read, cost);
getline(read, pric);
getline(read, quan);
getline(read, readSpace); // store space as well
}// end while
// reset counter
counter = 0;
// reposition to beginning and close files
read.clear();
read.seekg(0);
read.close();
write.close();
// open files again
read.open("temp.txt");
write.open("Printers.txt",ios::out);
write << ""; // clear original file
// read from temp file
getline(read, num);
getline(read, name);
getline(read, manu);
getline(read, type);
getline(read, reso);
getline(read, cost);
getline(read, pric);
getline(read, quan);
getline(read, readSpace); // store space as well
while(!read.fail())
{
// write back to the original file the amended information
write << num << endl // insert new item numbering
<< name << endl
<< manu << endl
<< type << endl
<< reso << endl
<< cost << endl
<< pric << endl
<< quan << endl
<< endl; // inserts a space between records
// read another record
getline(read, num);
getline(read, name);
getline(read, manu);
getline(read, type);
getline(read, reso);
getline(read, cost);
getline(read, pric);
getline(read, quan);
getline(read, readSpace); // store space as well
}// end while
// reposition to beginning of temp file and close files
read.clear();
read.seekg(0);
read.close();
write.close();
// open temp and clear contents
write.open("temp.txt", ios::out);
write << "";
write.close();
}