C ++ does not have a standard mechanism for trimming a file at a given point. You either need to recreate the file (open with ios::trunc and write the content you want to save), or use the API calls for the OS ( SetEndOfFile on Windows, truncate or ftruncate on Unix).
EDIT: Removing material in the middle of a file is extremely dangerous. Long before considering any other alternatives, I would try to use a server-side database engine, such as SQLite, to store serialized objects. Even better, I would use SQLite as intended by storing the data needed by these objects in the correct schema.
EDIT 2: If the problem instruction requires access to the unprocessed file ...
As a rule, you do not delete data from the middle of the file. If the objects can be serialized to a fixed size on the disk, you can work with them as records, and instead of trying to delete the data, you use a table that indexes the records in the file. For example, if you record four records in sequence, the table will contain [0, 1, 2, 3] . To delete the second entry, you simply delete its entry from the table: [0, 2, 3] . There are at least two ways to reuse the holes left by the table:
- In each insert, scan the first unused index and write the object to the appropriate recording location. It will be more expensive though, as the file grows.
- Keep a free list. Store the index of the most recently released record as a separate variable. In the space occupied by this record, the index of the freed record is encoded, etc. This maintains a handy list of free entries, but it only requires one extra number. However, itβs more difficult to work with, and an additional I / O disk is required during removal and insertion.
If the objects cannot be serialized to a fixed length, then this approach becomes much more complicated. The variable length write control code is very complex.
Finally, if a task operator requires saving records to disk on disk, then this is a stupid problem, because inserting / deleting in the middle of a file is ridiculously expensive; no reasonable design would require this.
source share