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);
uj5u.com熱心網友回復:
TStringList(Classes) 更簡單
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;
uj5u.com熱心網友回復:
我只是想為 OP 關于@Para 答案的問題添加一些解釋。
您可以創建一個 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;
uj5u.com熱心網友回復:
由于多種原因,您顯示的代碼無法編譯。
在任何情況下,要做你想做的事,只需ReadLn()在回圈中呼叫,比較讀取的內容,如果你檢測到你正在尋找的字串,然后設定 aBoolean并退出回圈。然后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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503935.html
標籤:德尔福
