views:

53

answers:

2

I want to write to a file without overwriting anything. It is a text file containing records. When I delete a specific record, I do not actually remove it from the file, I just put information in the header saying that it is deleted. How can I do this?

+2  A: 

You cannot append to the BEGINNING of a file without having to rewrite it from scratch. It has to go at the end (which makes sense, since that's what the word "append" means).

If you want to be able to flag a record as deleted without reserving space for that flag, you'll need to place the information at the end, or rewrite everything.

A more sensible approach is indeed to reserve the space upfront - for example by placing a "deleted" field in each record.

Michael Madsen
What if I reserve blank space at the beginning where I can store information about which files are deleted?
Phenom
@Phenom, that's what he's suggesting. Great idea btw (+1 @ Michael).
Cam
He was suggesting reserving space upfront by putting a field in each record. I am actually talking about reserving space at the front of the file.
Phenom
As long as you reserve the space, that's fine and you can mark a record as deleted by just seeking to the correct place and overwriting that one flag. Using a field in the record was just an example. However, remember that if it's not part of the record, you'll be forced to rewrite at least parts of the file if you have to add new records. Depending on what you're doing with the records, then it might really make more sense to use a flag in the record itself.
Michael Madsen
A: 

One possible solution is if there are certain characters which are normally dissallowed in records (it seems like each file is a record - please correct me if I'm wrong):

Use these characters in combination with some number of word flag (eg. #deleted#, or #000 if # is a character not normally allowed in records).

Then just overwrite whatever happens to be at the beginning of the record; it's deleted anyways so it shouldn't matter that you're overwriting part of it.

On the other hand, this probably isn't a good idea if you anticipate ever needing to recover 'deleted' files.

By the way - if you do append (at the end of the file) the deleted flag, note that it's very easy to check for it if you know the file size - just look at the end of the file.

Cam