Home > database >  How to check if data exits in a textfile and if it does it must not save the same data and show a me
How to check if data exits in a textfile and if it does it must not save the same data and show a me

Time:08-09

Var
MyFile : Textfile;
shine: String;
Begin
AssignFile(myfile, 'Username.txt');
Reset ( myFile);
 While not EOF(myFile) do
If sLine = edtEnterUser.Text then
Begin
ShowMessage ('Username already exists')
Begin
ReadLn(myFile,sLine);
end
else
Append(myFile);
CloseFile(myFile);

CodePudding user response:

TStringList(Classes) is simpler

var
  sl: TStringList;
begin
  sl := TStringList.Create;
  try
    sl.LoadFromFile('Username.txt');
    if sl.IndexOf(edtEnterUser.Text) > -1 then
      ShowMessage ('Username already exists');
  finally
    sl.Free;
  end;
end;

CodePudding user response:

I just wanted to add some explanation for OP's questions regarding @Para's answer.

You can create a TStringList class, make it load any file with encoding if required and manipulate it then save it again. Explination:

var
  sl: TStringList;
begin
  sl := TStringList.Create; // Create the stringlist
  try // Run the code inside a try block so that if an exception gets thrown it will still free the stringlist to prevent a memory leak.
    sl.LoadFromFile('Username.txt', TEncoding.UTF8); // Load the text inside the file.
    if sl.IndexOf(edtEnterUser.Text) > -1 then // If the index is greater than -1 then it exists however if it's -1 then it doesnt exist
      ShowMessage ('Username already exists')
    else
    begin
      sl.add(edtEnterUser.Text); // If it doesnt exist then add it.
      sl.SaveToFile('Username.txt', TEncoding.UTF8); // save to the file.
    end;
  finally
    sl.Free; // Lastly free the stringlist from memory. This code will run regardless if there are errors.
  end;
end;

CodePudding user response:

The code you have shown does not compile, for several reasons.

In any case, to do what you want, simply call ReadLn() in a loop, comparing what was read, and if you detect the string you are looking for then set a Boolean and exit the loop. Then check the Boolean after the loop is finished. For example:

var
  MyFile: TextFile;
  sUser, sLine: String;
  bFound: Boolean;
begin
  sUser := edtEnterUser.Text;
  AssignFile(MyFile, 'Username.txt');
  Reset(MyFile);
  bFound := False;
  while not EOF(MyFile) do
  begin
    ReadLn(MyFile, sLine);
    if sLine = sUser then
    begin
      bFound := True;
      Break;
    end;
  end;
  if bFound then begin
    ShowMessage('Username already exists');
  end else
  begin
    CloseFile(MyFile);
    Append(MyFile);
    WriteLn(MyFile, sUser);
  end;
  CloseFile(MyFile);
end;
  • Related