Hi im writing a function in a program that lets the user delete a specific record in a file, the user is also able to recover this record. The easiest way i found is when the record is deleted, the record will be set to deleted using bool. Then in my print function it will only print the records that are marked "deleted = false". If the user wants to recover the record it will set the deleted = false and print the record again. But i can't find a way to implement this.
So any ideas on how to delete a record from a file? And able to recover it later. Ive searched through online fstream tutorials and can't find any. The only one was quite helpful was to delete the contents of the file, make the modifications, then reprint the file. But how am i suppose to recover the record later? If i print the read record in delete() it prints the record perfectly.
Heres my code:
void delete()
fstream DeleteFile;
PersonStruct tmp1;
bool deleted = false;
int recordPos;
int pos;
DeleteFile.open( "H:\\FILE", ios::binary | ios::in | ios::out );
cout << "Delete Record: ";
cin >> recordPos;
pos = position(recordPos);
if (pos == -1)
cout << "file does not exist";
else
{
DeleteFile.seekp(0, ios::beg); //set pointer to start of file
DeleteFile.seekp(pos * sizeof(tmp1), ios::beg); //set pointer to the position of the record
DeleteFile.read((char*) &tmp1, sizeof(tmp1)); //read the record from the start to the end of the record
}
int position(int recordPos)
{
fstream SearchFile;
PersonStruct tmp1;
int pos = 0;
SearchFile.open( "H:\\FILE", ios::binary | ios::in | ios::out );
while ( !SearchFile.eof())
{
SearchFile.read((char*) &tmp1, sizeof(tmp1));
if ( tmp1.pos == recordPos)
{
return pos;
break;
}
++pos;
}
SearchFile.close();
return -1;
}