Deleting Text File Record
Hello,
I am trying to write a function that searches for, and deletes, a particular record in a text file. I am trying to achieve this by creating a temporary file, copy everything except the record i want to delete, delete the original file, and then rename the temp file using the original name. However, my code does not delete the record, and instead, sometimes copies the contents of the original file and appends.
Can anyone tell me where I went wrong, or show me a better way. Thanks in advance.
Code:
void POS::deleteRecord(char fileName[], string itemNum)
{
ofstream write;
ifstream read;
counter = 0;
string num, name, manu, type, reso, cost, pric, quan;
read.open(fileName);
write.open("temp.txt", ios::out);
write << ""; // empty the file just in case;
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);
while (!read.fail())
{
if (itemNum.compare(num)== 0) // is item number == to our search item?
{
num = "";
name = "";
manu = "";
type = "";
reso = "";
cost = "";
pric = "";
quan = "";
readSpace = "";
continue; // skip and move to the next record
}
else
{
counter++;
// store only valid records (quantity > 0)
write << counter << endl
<< name << endl
<< manu << endl
<< type << endl
<< reso << endl
<< cost << endl
<< pric << endl
<< quan << endl
<< endl;
}// end else
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);
}// end while
read.close();
write.close();
// delete the original file
remove (fileName);
int result;
// rename the temp file to original name
result = rename("temp.txt", "Printers.txt");
if (result == 0)
cout << " Successfully!";
else
cout << " Unsuccessful!";
remove("temp.txt");
// reset counters
counter = 0;
}