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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With