Compile with gcc:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
// Prepend size must be less than this value
#define bufSize 1024000
int main( int argc, char **argv )
{
FILE *fil;
unsigned char *smallBuf, *mainBuf;
size_t sReadSize, mReadSize;
long readPos = 0, writePos = 0;
int appendSize;
if( argc != 3 )
{
printf( "Usage: %s, <prepend_line> <file>\n", argv[0] );
return 1;
}
sReadSize = appendSize = strlen( argv[1] ) + 1;
smallBuf = (unsigned char *) malloc( appendSize );
mainBuf = (unsigned char *) malloc( bufSize );
if( !smallBuf || !mainBuf )
{
printf( "No memory\n" );
return 1;
}
memcpy( smallBuf, argv[1], appendSize );
smallBuf[ appendSize - 1 ] = '\n';
fil = fopen( argv[2], "rb+" );
if( !fil )
{
printf( "Cannot open file\n" );
return 1;
}
while( 1 )
{
fseek( fil, readPos, 0 );
readPos += mReadSize = fread( mainBuf, 1, bufSize, fil );
fseek( fil, writePos, 0 );
writePos += fwrite( smallBuf, 1, sReadSize, fil );
if( mReadSize < bufSize )
{
if( mReadSize > 0 )
fwrite( mainBuf, 1, mReadSize, fil );
break;
}
fseek( fil, readPos, 0 );
readPos += sReadSize = fread( smallBuf, 1, appendSize, fil );
fseek( fil, writePos, 0 );
writePos += fwrite( mainBuf, 1, mReadSize, fil );
if( sReadSize < appendSize )
{
if( sReadSize > 0 )
fwrite( smallBuf, 1, sReadSize, fil );
break;
}
}
fclose( fil );
return 0;
}