Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a specific line from a text file in Delphi

I have a text file with user information stored in it line by line. Each line is in the format: UserID#UserEmail#UserPassword with '#' being the delimiter.

I have tried to use this coding to perform the task:

var sl:TStringList;
begin
  sl:=TStringList.Create;
  sl.LoadFromFile('filename');
  sl.Delete(Index);
  sl.SaveToFile('filename');
  sl.free;
end;

But I'm not sure what to put in the "index" space.

Is there any way I can receive the User ID as input and then delete the line of text from the text file that has this user ID in? Any help would be appreciated.

like image 802
Mark van Heerden Avatar asked Aug 18 '16 15:08

Mark van Heerden


People also ask

How do you delete a line in a text?

Place the text cursor at the beginning of the line of text. On your keyboard, press and hold the left or right Shift key and then press the End key to highlight the entire line. Press the Delete key to delete the line of text.

How do I delete a Delphi text file?

Delphi Basics : deletefile command. The DeleteFile function deletes a file given by its file name FileName. The file is looked for in the current directory. If the file was deleted OK, then True is returned, otherwise False is returned.

How do you delete a specific line in a file in C?

An algorithm is given below to explain the C program to remove a line from the file. Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file.


1 Answers

You can set the NameValueSeparator to # then use IndexOfName to find the user, as long as the username is the first value in the file.

sl.NameValueSeparator := '#';
Index := sl.IndexOfName('455115')

So in your example, like so

var sl:TStringList;
begin
  sl:=TStringList.Create;
  sl.LoadFromFile('filename');
  sl.NameValueSeparator := '#';
  Index := sl.IndexOfName('455115')
  if (Index  <> -1) then
  begin
      sl.Delete(Index);
      sl.SaveToFile('filename');
  end;
  sl.free;
end;

This may be slow on large files as IndexOfName loops though each line in the TStringList and checks each string in turn until it finds a match.

Disclaimer: Tested/ works with Delphi 2007, Delphi 7 may be diffrent.

like image 86
Re0sless Avatar answered Sep 20 '22 15:09

Re0sless