• 13
• 18
• 19
• 27
• 10

# Deleting objects from files?(C++)

This topic is 3942 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi there, I am creating a simple C++ program which involves writing objects to files.Is there any way to delete a specific object when it is irrelevant.The location of the object might be anywhere in the file. Thanks.

##### Share on other sites
Yes. You find the location of the object in the file, then mark it as deleted.

Usually, you'll maintain an array of offsets somewhere in the file, that contains the file information and an offset into where the object is stored.

When you delete an object, you just need to update the index table with a flag indicating an object no longer exists.

Obviously, you'll end up with delete objects still stored in the file and taking up space, but they can no longer be read.

Anything above that requires techniques employed by file systems - namely how to manage free space and holes, how to minimize wasted space, how to store files of arbitrary sizes, etc...

The other option is to recreate entire file from scratch each time you manipulate it.

Third option completely removes the problem, and is the one most commonly used - when starting the application, you restore full state from file. When the application shuts down (or on explicit request) you write entire state again.

But fully differential on demand manipulation with little/no overhead is an extremly complex topic that doesn't have an optimal solution. File systems are targetted at specific roles. Some are good at updating, some at reading large files, some at random access. But no file system is good at everything.

##### Share on other sites
Thank you very much.Good ideas there.I think that I might be going for the first one.But can you please tell me what an array of offsets is??Sorry a newbie here..

##### Share on other sites
Quote:
 Original post by sciphiThank you very much.Good ideas there.I think that I might be going for the first one.But can you please tell me what an array of offsets is??Sorry a newbie here..

Just an array in the file (perhaps in the beginning) that determines where in the file your objects start. If you have one object that starts at offset 16, the next at offset 50, and the last at offset 63, your array might look like this (4 byte values):

 [3 /*number of elements in this array */, 16, 50, 63]

And you could perhaps mark objects as deleted by setting the offset to 0 (that would work, as in my example no objects can ever be at offset zero, because that would be where the array is).