Mirror

How to delete lines from a text file (Views: 100)


Problem/Question/Abstract:

How can I open a file and add lines which start with PIL to a listbox. When I delete the appropriate line in the listbox, the line in the file should also be deleted.

Answer:

Load the complete file into a TStringList instance. Then iterate over the Items in the list and use the Pos function to check if the line starts with PIL, if it does you add it to the listbox. When time comes to save the possibly changed file back you again walk over the items in the listbox, but this times you do it from last to first. For each line that starts with PIL you use the listbox.items.indexof method to see if it is in the listbox, if not you delete it from the stringlist. Then you write the stringlist back to file. Example:

In the forms private section you declare a field

FFilelines: TStringList;

In the forms OnCreate event you create this list:

FFilelines := TStringList.Create;

In the forms OnDestroy event you destroy the list:

FFilelines.Free;

On file load you do this:

FFilelines.Loadfromfile(filename);
listbox1.items.beginupdate;
try
  listbox1.clear;
  for i := 0 to FFilelines.count - 1 do
    if Pos('PIL', FFilelines[i]) = 1 then
      listbox1.items.add(FFilelines[i]);
finally
  listbox1.items.endupdate;
end;

To save the file you do this:

for i := FFilelines.count - 1 downto 0 do
  if Pos('PIL', FFilelines[i]) = 1 then
    if listbox1.items.indexof(FFilelines[i]) < 0 then
      FFilelines.Delete(i);
FFilelines.SaveToFile(filename);

<< Back to main page