How to write a line to the beginning of a file ? [Archive] - C Board

PDA

View Full Version : How to write a line to the beginning of a file ?


meili100
04-03-2008, 12:57 PM
FILE* fp = fopen(filename,"a")

appends lines to the file, how to write to the beginning of the file? Is there a way?

Suppose the file is very large and I don't want to the following: "read the former content to a buffer, add the line to the beginning, then dump all buffer back to the file"

brewbuck
04-03-2008, 01:05 PM
FILE* fp = fopen(filename,"a")

appends lines to the file, how to write to the beginning of the file? Is there a way?

Suppose the file is very large and I don't want to the following: "read the former content to a buffer, add the line to the beginning, then dump all buffer back to the file"

If you don't want to buffer in memory, then you buffer on disk. Either way, some buffering must occur.

To buffer on disk, create a temporary file. Write the new line to the file. Then open the other file and append all its data to the temporary file. Then remove the original file and rename the temporary back to the original name. If you are going to be adding lines repeatedly, this is obviously extremely inefficient.