-
Deleting part of a file
Does anyone know how to delete a record from a file? I had an algorithm that would take the next record in the file and write it over the previous record and so on until there were 2 like records at the end of the file, but how would one go about completely removing the bytes of one record from a file? I thought maybe truncate, but that resets the entire file to 0bytes right?
-
The way I solved a similar program where I had abstract data in a custom linked list was using copy, remove, and write.
- read data from file into a data structure
- remove whatever data you want
- remove(filename) // delete the data file
- write new data file with the updated data structure
Kuphryn
-
Yep, that's the only way...'cept another way to 'erase' the file, without calling remove is:
FILE *f = fopen(bFile, "r+");
//..read in, delete entries - then:
int handle = fileno( f );
chsize( handle );
-
Well, Sebastiani, that's C, but I suppose I could open the file with ios_base::trunc and truncate it to 0bytes effectively deleting the entire contents of the file. Then I could rewrite the data minus the record I want to delete. That seems like an enourmous load just to delete one record though...
Any other thoughts on deleting just one part of a file?
Thanks for you suggestions, Invincible
-
There is no other way.
What's so hard, anyway?
BTW: I am a halfling. Half C, half C++.
-
Ahh, it's not that it's overly difficult to code, but that it seems like a work-around for what should be a standard library function. That's all.
Friends don't let friends mix C and C++
Halfling ... bah ... I am an ogre. I eat halflings :D
Edit:
Just think of it this way...
to delete one file, you're allocating (record[bytesOfMemory] * numberOfRecords) just to remove one record from a file. Depending on the number and size of the records, that could be a very inefficient way of doing things.