1
votes

I have a .txt file and I want to replace a line with a new one. These are the steps:

  1. Read in the .txt file
  2. Save Source to a TStringList
  3. Modify some data in a particular line
  4. Save the new data back to the original file.

How do I do this?

3

3 Answers

8
votes

Like this:

var
  Strings: TStringList;
....
Strings := TStringList.Create;
try
  Strings.LoadFromFile(FileName);
  Strings[LineIndex] := NewValue;
  Strings.SaveToFile(FileName);
finally
  Strings.Free;
end;
3
votes

With newer Delphi's you can get the contents of a file as an array of strings in a single call TFile.ReadAllLines().

program TestModifyLine;  {$APPTYPE CONSOLE}
uses Types,IoUtils;

procedure ModifyLine(fn:string;Index:integer;NewText:String);
var lines:TStringDynArray;
begin
  lines := TFile.ReadAllLines(fn);
  lines[Index] := NewText;
  TFile.WriteAllLines(fn,lines);
end;

begin
  ModifyLine('test.txt',12,'hello');
end.
1
votes

If you don't want to waste memory loading the entire source file at one time, you can use TStreamReader and TStreamWriter to read/write the files one line at a time, modifying the desired line after reading it and before writing it.

Var
  Reader: TStreamReader;
  Writer: TStreamWriter:
  Line: String;
  LineNum: Integer;
Begin
  Reader := TStreamReader.Create(...);
  Writer := TStreamWriter.Create(...);
  While not Reader.EndOfStream do
  Begin
    Line := Reader.ReadLine;
    Inc(LineNum);
    If LineNum = ... Then
    Begin
      ...
    End;
    Writer.WriteLine(Line);
  End;
  Writer.Free;
  Reader.Free;
End;