Today’s problem is that I need to write an array of numbers in a binary file at a starting position. I have the position where it should start, and I don’t want to overwrite values after that, just want to insert the array at the starting position in the file. E.g:
12345
Let’s push 456 at position 2:
12456345
I know that probably I’ll have to implement it by myself, but I want to know what’s your opinion on how to implement that as efficiently as possible.
Here’s a function
extend_file_and_insert()that does the job, more or less.(Note the additional line added 2013-07-19; it was a bug that only shows when the buffer size is smaller than the amount of data to be copied up the file. Thanks to malat for pointing out the error. Code now tested with
BUFFERSIZE = 4.)This is some small-scale test code:
It produces the output:
It should be tested on some larger files (ones bigger than BUFFERSIZE, but it would be sensible to test with a BUFFERSIZE a lot smaller than 64 KiB; I used 32 bytes and it seemed to be OK). I’ve only eyeballed the results but the patterns are designed to make it easy to see that they are correct. The code does not check any of the
lseek()calls; that’s a minor risk.