How to add a new line to the beginning of a file without overwriting any data?

I am trying to figure out how to write a new line of text at the beginning of the file (header). I know that I can open the file or look for the beginning of the file, but if I write with it, it will overwrite what is there. Should I write a new file and then write other data into 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 finish 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:

Here is what I did:

 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"); 
+4
source share
3 answers

You will have to rewrite the entire file, but this does not necessarily mean that you need to read and write the source data in turn. Reading lines is relatively slow, so if the file is small enough to fit into memory, read it all in one large fragment (or in large blocks), and then write it down after writing new data.

+6
source

Well, probably the simplest thing is to notice that what you want to do is equivalent to the unix cat . If you use unix, you can just call it from c. Or you can read the source in gnu textutils.

But in any case, all these solutions just rewrite the file!

+1
source

You need to open a new file and write again.

0
source

All Articles