Search code examples
cfileio

Prepend text to a file in C


I want to add a standard header to a file (or group of files) using C. These files could be quite large, so it would be a bad idea to load them into memory, or copy them into temporary files (I think).

Is there a way to simply prepend the header directly to each file?

The header itself is quite small, not more than 1 KB


Solution

  • It should be possible without a temporary file - you can read the file from the end, block by block, writing each block back at (original_position + header_size). The first block would be written back at header_size, leaving room for the header.

    However, you don't really want to do this. It would corrupt the file if aborted (think: out of disk space, other I/O error, power down, whatever).

    Thus, you should actually use temporary file - write to it everything you need, then rename it to the original file's name (assuming you create temporary file on the same file system, otherwise you'd need to copy).

    Edit: to clarify what I mean, simplified solution when the whole file fits in RAM:

    • allocate buffer same size as the file
    • open the file, and read it into the buffer
    • seek(file, header_size) and write the buffer here
    • seek(file, 0) write the header

    If the file is to big, you can allocate smaller buffer and repeat reads/writes starting with read at file_size - buffer_size and write at file_size - buffer_size + header_size. Then repeat with next chunk read at file_size - 2 * buffer_size, write at file_size - 2 * buffer_size + header_size, and so on.

    But let me repeat: you risk corrupting your file if it fails!