Thread: How to write a line to the beginning of a file ?

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    How to write a line to the beginning of a file ?

    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"
    Last edited by meili100; 04-03-2008 at 01:01 PM.

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by meili100 View Post
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM