Thread: Appending data

  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Rep Power

    Question Appending data

    How we can append data in middle of file through c code
    ex -original file contents
    First line
    Second line
    now the file contents
    Firts line
    New line
    second line
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Rep Power

    You mean: Inserting data into the middle of a file

    Of course, it all depends on how you have organized your file. For example, some file formats would index its records so that new records are appended to the end of the file and the index would report that new record's position among the other records. Of course, such formats can be complex.

    Rather, I assume that you want to insert new data into the middle of a simple sequential file. Try to think about it as you would insert a new item into the middle of an array: everything that will come after the new data needs to be moved to the right one position. You effectively need to do the same thing to the file.

    One approach would be:
    1. Open a temporary file.
    2. Copy from the original file to the new file every line that precedes the new line.
    3. Write the new line to the new file.
    4. Write the rest of the original file to the new file.
    5. Delete the original file.
    6. Rename the temporary file to the original file's name.

    For most smaller files, that should work fine. If the file becomes too large, then you may need to turn to a more complex file format.

IMN logo majestic logo threadwatch logo seochat tools logo