delphi 如何检查数据是否存在于文本文件中,如果存在,则不能保存相同的数据,并显示一条消息,说明数据已存在

enxuqcxy  于 2022-11-04  发布在  其他
关注(0)|答案(3)|浏览(199)
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);
q5iwbnjs

q5iwbnjs1#

TStringList(类)更简单

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;
pftdvrlh

pftdvrlh2#

我只是想补充一些关于@帕拉的回答的OP问题的解释。
你可以创建一个TStringList类,如果需要的话,让它加载任何带有编码的文件,并操作它,然后再次保存它。

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;
y4ekin9u

y4ekin9u3#

您所显示的程式码无法编译,原因如下。
在任何情况下,只要在循环中调用ReadLn(),比较读取的内容,如果检测到要查找的字符串,则设置Boolean并退出循环。然后在循环结束后检查Boolean。例如:

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;

相关问题