I'm trying to implement a program that Deletes a Record in a binary file without the use of a temporary file.
The code I've written works perfectly fine in deleting a record except there is an obvious error.Code:class Manager { private: int ID; char Name[20]; public: void AddRecord (void); void DeleteRecord (void); void DisplayRecords (void); }M; void Manager::DeleteRecord (void) { clrscr (); int SearchID; cout << endl << " CHOICE: Delete Record!" << endl; fstream fin ("Manager.dat" , ios::in | ios::nocreate | ios::binary); if (!fin) cout << endl << " Error!" << endl; else { cout << endl << " Enter ID (to be deleted): "; cin >> SearchID; bool found = false; fstream fout ("Manager.dat" , ios::out | ios::ate | ios::binary); if (!fout) cout << endl << " Error!" << endl; fout.seekp (0 , ios::beg); while (fin.read ((char*)this , sizeof(Manager))) { if (SearchID == ID) { found = true; continue; } fout.write ((char*)this , sizeof(Manager)); } fout.close(); if (!found) cout << endl << " No Records with ID: " << SearchID << " found!" << endl; fin.close (); } }
Initial content in my file:
1 A
2 B
3 C
4 D
In my initial file, if I choose to delete record with ID = 4, I get:
1 A
2 B
3 C
4 D
In my initial file, if I choose to delete record with ID = 3, I get:
1 A
2 B
4 D
4 D
In my initial file, if I choose to delete record with ID = 2, I get:
1 A
3 C
4 D
4 D
In my initial file, if I choose to delete record with ID = 1, I get:
2 B
3 C
4 D
4 D
What I can observe from this is that the actual data that I want to delete is being deleted but the No. of Records is still remaining 4 (the 4th one always being "4 D" in this case).
If I take my class size as 22 Bytes( int ID being 2 on Turbo , char Name[20] being 20 ), then my file size results in 88 Bytes. So, when I delete a record my file size should end up being 66 Bytes but I do not know how to implement that. My file remains 88 Bytes as the last record always remains.
How can I fix this?
Thanks!