I am trying to figure out how to write a new line of text at the beginning of a file (a header). I know I can open the file, or seek to the beginning of a file, but if I write with that, it will overwrite what's there. Do I have to write a new file and then write the other data to it line by line, or is there a better way?
Example file:
1, 01/01/09, somedata, foo, bar
2, 01/02/09, somedata, foo, bar
3, 01/03/09, somedata, foo, bar
And I want to end up with
3, 1-3, 01/04/09
1, 01/01/09, somedata, foo, bar
2, 01/02/09, somedata, foo, bar
3, 01/03/09, somedata, foo, bar
EDIT:
This is what I ended up doing:
FILE *source;
FILE *output;
char buffer[4096];
size_t bytesRead;
memset(buffer, 0, sizeof(buffer);
source = fopen("sourcefile.txt", "r");
output = fopen("output.txt", "w+");
fprintf(output, "my header text\n");
while(!feof(source))
{
bytesRead = fread(&buffer, 1, sizeof(buffer), source);
fwrite(&buffer, 1, bytesRead, output);
}
fprintf(output, "my footer text");
fclose(source);
fclose(output);
remove(source);
rename("output.txt", "source.txt");