Delete record from file C++

4.2k views Asked by At

I'm working on a simple database console application in C++ for adding, editing and deleting records in a .dat file. I have the addition and modification down, I'm just finding it hard to understand the concept of deletion in this scenario. Below is how I write a record.

Write record

fh.seekp(num*sizeof(customerObj),ios::beg); // Move the write pointer to where rec is
fh.write((char*)&customerObj,sizeof(customerObj)); // Write updated rec

Any ideas how instead of write() I could have something equivalent to delete()... or is it not that simple?

3

There are 3 answers

8
Alexey Frunze On BEST ANSWER

C and C++ don't have functions to delete parts of files. Many operating systems don't either.

Possible options:

  1. If this is the last record, truncate the file. If not, move (=copy) all records after it, overwriting it, then truncate. Alternatively you could move (=copy) the last record to it and then truncate.

  2. Create an extra file and copy to it all records before this and after this record. Then delete the old file and rename the new file.

  3. Mark the record as unused. When writing new records check if you have any unused locations and use them first.

  4. Use a file per record.

0
Dewfy On

Introduce marker of deleted record. So instead of movement of large chunks of file you need write 1 symbol. When you need allocate new record you could iterate over already deleted and just remove marker.

0
giorashc On

Well, deleting from files is not trivial as you cannot delete a row from a file directly. One approach is to read the entire file (or in bulks) and write it back without the required line. (quite robust and not efficient for large files).

Maybe if you divide you record file into smaller partitioned files than doing the above will be more efficient.

Another thing you can do is just mark a row in the file as invalid (as done in memory when deleting a pointer) and overwrite it when needed which of course depends on how you write your records but I hope you get what I mean.