August 18th, 2003, 08:32 AM
-
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 ?
August 18th, 2003, 02:03 PM
-
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.