[Q] Deleting records in flat files

  • Thread starter Thread starter Stuart Norris
  • Start date Start date
S

Stuart Norris

Dear Readers,

I am developing an application that stores "messages" in array list
and writes new entries to a disk file at the end. This file is used
incase the user choses to restart the program. When the program is
restarted the messages are replayed so the application knows where it
is up to.

I am not allowed to use a **database** I have been instructed to use a
flat file. The application I am replacing does that.

Everything works fine until someone wants to delete a message from the
list. In the Arraylist I simply remove the entry. Which is easy.

However for the file I re-create (delete and re-create) the entire
file with the new records - which seems a waste and exposes possible
danger if the users shuts the application down while re- creating the
file. I know this is small, but I would like to remove all risks.

I am writing the file as binary file stream, with a "message" length
followed by the variable length messages.

Is there any way I can deleted records in the centre of the file
without recreating the file?

Failing deleting the records is there a way I could rewrite a record
in the current file to indicate it should not be reloaded on restart.
I have plenty of space free in the records for some flag.

I know that a database is a better way to do this however I have been
told not to use a database.



Any suggestions.

Stuart
 
Why don't you simply rewrite the date in a *new* file, and after everything
has been written, delete the old file and rename the new file with the name
of the original file.
 
Hi Stuart,

Cody has the best answer... and the most common method for solving that
problem.

If the file is really huge, and you don't feel like rewriting it, you could
add a field to your data that sets a "deleted" value. Use the Seek() method
to move to a specific file location. You will have to track the location of
every record you read, and when you user "deletes" it, move to the location
and mark the record as "deleted." Then, when you re-read it, skip this
record. This is a lousy method unless you control everything going into
and out of your file, so really, you should use Cody's solution first. (in
fact, if you have less than 100,000 records, I'd nominate this solution as
the biggest waste of time imaginable).

--- Nick
 
Back
Top