I have a .txt file and I want to replace a line with a new one. These are the steps:
- Read in the .txt file
- Save Source to a TStringList
- Modify some data in a particular line
- Save the new data back to the original file.
How do I do this?
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.
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;