I need to Erase the file contents from a selected Point (C++ fstream) which function should i use ?
i have written objects , i need to delete these objects in middle of the file
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
C++ has no standard mechanism to truncate a file at a given point. You either have to recreate the file (open with
ios::truncand write the contents you want to keep) or use OS-specific API calls (SetEndOfFileon Windows,truncateorftruncateon Unix).EDIT: Deleting stuff in the middle of a file is an exceedingly precarious business. Long before considering any other alternatives, I would try to use a server-less database engine like SQLite to store serialised objects. Better still, I would use SQLite as intended by storing the data needed by those objects in a proper schema.
EDIT 2: If the problem statement requires raw file access…
As a general rule, you don’t delete data from the middle of a file. If the objects can be serialised to a fixed size on disk, you can work with them as records, and rather than trying to delete data, you use a table that indexes records within the file. E.g., if you write four records in sequence, the table will hold
[0, 1, 2, 3]. In order to delete the second record, you simply remove its entry from the table:[0, 2, 3]. There are at least two ways to reuse the holes left behind by the table:If the objects can’t be serialised to a fixed-length, then this approach becomes much, much harder. Variable-length record management code is very complex.
Finally, if the problem statement requires keeping records in order on disk, then it’s a stupid problem statement, because insertion/removal in the middle of a file is ridiculously expensive; no sane design would require this.