merlin2011
merlin2011

Reputation: 75575

What's a short way to prepend 3 bytes to the beginning of a binary file in C?

The straightforward way I know of is to create a new file, write the three bytes to it, and then read the original file into memory (in a loop) and write it out to the new file.

Is there a faster way that would either permit skipping the creation of a new file, or skip reading the original file into memory and writing back out again?

Upvotes: 2

Views: 372

Answers (3)

geekosaur
geekosaur

Reputation: 61389

This isn't so much about C as about filesystems; there aren't many common filesystem APIs that provide shortcuts for prepending data, so in general the straightforward way is the only one.

You may be able to use some form of memory-mapped I/O appropriate to your platform, but this trades off one set of problems for another (such as, can you map the entire file into your address space or are you forced to break it up into chunks?).

Upvotes: 1

tomlogic
tomlogic

Reputation: 11694

You could open the file as read/write, read the first 4KB, seek backward 4KB, write your three bytes, write (4KB - 3) bytes, and repeat the process until you reach the end of the file.

Upvotes: 0

user149341
user149341

Reputation:

There is, unfortunately, no way (with POSIX or standard libc file APIs) to insert or delete a range of bytes in an existing file.

Upvotes: 1

Related Questions