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 开发者_C百科put information in the header saying that it is deleted. How can I do this?
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.
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.
精彩评论