Possible Duplicate:
C write in the middle of a binary file without overwriting any existing content
I am writing a program that occasionally needs to insert 1-64k of data at the beginning of a binary file. The POSIX API / Linux ABI does not have an insert(fd,buf,len) function call. What’s the most efficient way to do this?
Your choices are:
The advantage of (2) is that it doesn’t break symlinks or multiple links to the original file. The disadvantage (as noted by Keith Thompson) is that if it is interrupted, you’ve lost your original file.
The disadvantage of (1) is that if you need to preserve numbers of links and work through symlinks, you have to copy the new file back over the old file, so there’s more copying. The advantage is that the copying is simpler and the original file is not destroyed until the end.
There’s another question with code for option (2) — Write in the middle of a binary file without overwriting any existing content. Inserting at the start of a (binary) file is just a specific (not even special) case of inserting in the middle of a file.