tags:

views:

235

answers:

3

I have a small code block that should append text to the beg of a file. However it still only adds to the end of the file. I thought the rewind set the pointer to the front of the file, thus when I added the text using fprintf it should add to the front. How can I change this?

fp = fopen("Data.txt", "a");
rewind(fp);
fprintf(fp, "%s\n", text);
fclose(fp);

Text is a char array to be added at the front of the file

+11  A: 

1) Don't open in append mode.

When you open in append mode, all writes go to the end of the file, regardless of the seek position.

http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html

Opening a file with append mode (a as the first character in the mode argument) shall cause all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek().

2) Opening without "a" still won't do what you want. It's not possible to insert into a file using the ANSI/POSIX file operations, because given the way most file systems store their data, insert is not a simple operation.

You need either to open a new file, write your new data, then append the old file afterwards, or else you need to mess around shuffling data forward in blocks. Either option is very inefficient for large files, compared with appending at the end, not to mention error-prone if you need the program or the machine to be able to unexpectedly die without corrupting data. So if this is a log file or similar, it's probably worth redesigning so that you can write new data to the end, and then reverse it all when you prepare a report from the log.

Steve Jessop
+4  A: 

You can replace data in a file, but you can't prepend or insert it anywhere but at the very end of the file.

Ryan
A: 

Just create a new file with your data and then append the old data in this file you created.

William