Removing bytes from a file (C++)

Soldato
Joined
7 Apr 2004
Posts
4,212
Hey,

I need a way to remove X number of bytes from a position inside a binary file.

Currently all I can think up is this:
Code:
-Read everything from the start of file upto the position of the first byte to remove.
-Write this out to a temp file
-Read everything from the last byte to be removed to EOF.
-Append this to temp file
-Delete original
-Rename temp file to original file name.
This algorithm however will require (TotalSize - BytesToRemove) in free space on the disk to operate, and as my file could be pretty big I would really like to avoid this requirement if possible?

Are there any alternative solutions?

Thanks,
Jack
 
What about :

1) seek forwards <position> + <X> bytes
2) read sizeof(buffer) bytes (depends how much RAM you want to spend on it, more = less seeks = faster) worth of data, or up to the end of file, whichever is larger, save as <count> bytes
3) seek back <count> + <X> bytes
4) write <count> bytes from buffer
5) if the buffer read did not hit end of file, seek forwards <X> bytes, goto 2)
else :
6) ftruncate() at current position
7) end

No temp file or extra space needed
 
Back
Top Bottom