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

This is a discussion on How to write a line to the beginning of a file ? within the Tech Board forums, part of the Community Boards category; FILE* fp = fopen(filename,"a") appends lines to the file, how to write to the beginning of the file? Is there ...

  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 02:01 PM.

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,270
    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, 02:19 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21