How to set end of file??
I just started file part in C++. I can edit record in file but when i delete problem's coming. I dont know how to set end of file in file. I mean say there are 5 records in employee file
Now i ask which employee name you want to delete . Now suppose that record is 2nd one so what is do is copy 3rd record to 2nd one 4th to 3rd one and 5th to 4th one. But the problem is that last record appears twice. I want to set end of file after 1st appearance of last record. Please tell me how can i do it?
And also if anybody has some other good way to delete records then kindly tell me that also.
The algorithm usually goes something like:
1. Open the record file.
2. Open the new file, or if it is the same, a temp file.
3. Read the records.
4. Write records that you want to keep to the new file.
5. Close and remove the old file.
5b. If necessary, rename the temp file to the old name.
Then you're done.
where fileptr is the open file pointer.
fseek(fileptr, 0L, SEEK_END);
That won't destroy old records.
Yes that algorithm i know it. But if i want to perform it in the way that i mentioned above then how to do it?
How can i write eof to the file?
EOF is just a stream signal for the end of the file, it has nothing to do with deleting a record from a file. If you want to do that, you need an algorithm like the one I talked about.
There is no standard way. However, most operating systems provide a "truncate" function which is used to reduce the size of a file. On POSIX systems this function is truncate() or ftruncate(). On Windows it is SetEndOfFile().
Originally Posted by chottachatri
Copying to a new file and then renaming is the only standard way to do it, but terribly inefficient.
That's why DBs don't really remove records from tables but only mark them as deleted... And reuse them on adding new records...
As vart hints, another way to solve the problem is to have a way to "remember" deleted records, rather than actually remove them from the file. This can be done in several ways.
Some possible options:
1. A linked list of deleted records.
Have a "header" record at the start of the file, which contains the first deleted record. In each of the next deleted records, store the NEXT deleted record. When deleting something, just link that into the header record and point the newly deleted record to what was previously in the header.
2. Have every record hold two fields to know if it's a deleted record and where the next deleted record is. [Could be made into ONE record if -1 is used to indicate "not deleted".
3. Another variant is to shuffle all the data to a "earlier" record, and keep all deleted records at the end. You still need to know how many or which records are deleted, but it may make the logic a bit simpler to store all deleted records at the end of the file.