Advertisement

Binary

Started by January 01, 2001 11:26 PM
1 comment, last by hellstorm01 24 years ago
I have a database that writes equally sized records to a single file in binary form. I cant seem to figure out how to remove or delete a record from the binary file. In other words I want the user to be able to delete a record after it has been saved at least once. I already know how to find the position of the record in the file. Im using C++ fstream class for binary output. Below is the code I use to write a record. The snippet is contained in a the CRecordInf class. void WriteBinary(unsigned long ulplace) { fstream Database("crec.bin", ios::out | ios::ate | ios::binary); streampos place = ulplace * sizeof CRecordInf; Database.seekg(place); Database.write((char*)this, sizeof CRecordInf) << flush; Database.close(); } So how can I just wipe the data of one record at a time??? Thanx
This depends on how you want to accomplish the deletion. For example Access uses a little trick where it stores a used/not used flag with each record. When the user deletes a record, it''s not actually removed from the file. It''s just marked as "not used". Then rather than constantly changing the file''s size when records are added and deleted, Access just recycles the records that are flagged as unused, allocating new ones only when necessary. Using the "Compact" tool is what actually forces the unused records to get deleted.

If you must remove the record from the actual file every time the user deletes a record, or if you want to make a compact-like utility for your files, it''s basically a very boring and rather slow process. In pseudocode:

Open a temporary file
Move the beginning of the database
While not at the deleted record
Copy the current record to the temporary file
Move to the next record
Skip the current record (this is the deleted record)
While not at end of file
Copy the current record to the temporary file
Move to the next record
Delete the original database
Rename the temporary file to the same name as the original DB

If the database file is not very large you should probably skip the temp file and do everything in memory.

-W.






Advertisement
Hmm, they''ve destroyed the indentation on the pseudocode in my last post. Just imagine that the 2 lines below each "While" are indented.

-W.

This topic is closed to new replies.

Advertisement