Alex Rivera | Logout

C write in the middle of a binary file without overwriting any existing content

Asked 2012-05-06T02:51:11.150
10

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.

Edit
Report

1 Answer

1

I'm agreeing with the others, but let me state the solution a bit differently:

  1. Get a temp filename (there are OS-specific calls for this)

  2. Copy your original file to the temp file (there are now two copies of the same file)

  3. Open the original file for "append".

  4. "Truncate" it to your insertion point

  5. Write your new data

  6. Open your temp file for "read"

  7. "Seek" to the insertion point (again, the call is OS-specific)

  8. Read to end-of-file in temp file; inserting into your original file (still open for "append").

  9. Close both files

  10. Delete temp file

answered 2012-05-06T04:20:41.637

Your Answer