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

    Join Date
    Aug 2003
    Posts
    1
    Rep Power
    0

    Cool Deleting Lines From a Text File


    Hi Guys!

    I want to delete a particular row from a space delimited text file which I am able to do by sending the backspace character.
    Though I am able to delete the required line, the file still shows the backspace characters and the number of characters in the file remains the same. I want to totally erase text from the file. How do I do that ?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    Basically speaking, adding or removing a line to or from the middle of a text file involves moving all the following lines, exactly the same as would need to be done in adding or removing a single array element to or from the middle of the array. Google for a discussion of the "insertion sort" for more details.

    Unless somebody has a cleaner or more elegant way:
    1. Open the text file for input.
    2. Create and open a temporary text file for output.
    3. Read in all the lines preceding the line you want to delete and write them to the output file.
    4. Now read in all the lines following the line you want to delete and write them to the output file. Of course you do not include the line you are deleting because that is how you delete it.
    5. Close both files.
    6. Delete the original text file.
    7. Rename the temp file to the original file's name. This replaces the original file with a newer version that has deleted the line in question.

    On a similar note, some applications, such as dBase III, would mark records that you deleted but still keep them in the file. That marking would tell the application to ignore that record. This kept dBase from having to go through that entire shifting of records every single time you deleted a record -- I think it originally ran on floppies, so that would have been excruciatingly slow. Then during maintenance you would run a command -- PACK, as I seem to recall -- that would basically run through the algorithm above and remove all the records marked as deleted.

IMN logo majestic logo threadwatch logo seochat tools logo