Best way for read and write a text file

廉价感情. 提交于 2019-12-05 08:24:45

5000 lines isn't a lot, unless the strings are very long.

The easiest way is to use a TStringList. There's no need to use a GUI control unless the user needs to see or edit the content.

var
  SL: TStringList;
  i: Integer;
begin
  SL := TStringList.Create;
  try
    SL.LoadFromFile(YourFileNameHere);
    for i := 0 to SL.Count - 1 do
    begin
      SL[i] := IntToStr(i) + ' ' + SL[i];
      // Do any other processing
    end;

    SL.SaveToFile(YourFileNameHere);
  finally
    SL.Free;
  end;
end;

If (as you say in a comment above) you need to do this in a TMemo for testing purposes, you can do it the same way:

Memo1.Lines.LoadFromFile(YourFileNameHere);
for i := 0 to Memo1.Lines.Count - 1 do
  Memo1.Lines[i] := IntToStr(i) + ' ' + Memo1.Lines[i];
Memo1.Lines.SaveToFile(YourFileNameHere);

Of course, the easiest way to do this would be to write a procedure that accepts a plain TStrings descendent of any sort:

procedure AppendValueToStrings(const SL: TStrings; 
  StartingValue: Integer);
var
  i: Integer;
begin
  Assert(Assigned(SL));  // Make sure a valid TStrings has been passed in
  for i := 0 to SL.Count - 1 do
  begin
    SL[i] := IntToStr(StartingValue) + ' ' + SL[i];
    Inc(StartingValue);
  end;
end; 

Then you can call it with either one:

SL := TStringList.Create;
try
  SL.LoadFromFile(YourFileNameHere);
  AppendValueToStrings(SL, 10);
  SL.SaveToFile(YourFileNameHere);
finally
  SL.Free;
end;

Memo1.Lines.LoadFromFile(YourFileNameHere);
AppendValueToStrings(Memo1.Lines, 10);
Memo1.Lines.SaveToFile(YourFileNameHere);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!