Title: How to read line-by-line and modify a textfile
procedure TForm1.Button1Click(Sender: TObject);
var
i, z: Integer;
f: TextFile;
t: string;
Data: array of string;
begin
if OpenDialog1.Execute then
begin
//Read line by line in to the array data
AssignFile(f, OpenDialog1.FileName);
Reset(f);
z := 0;
SetLength(Data, 0);
//Repeat for each line until end of file
repeat
Inc(z);
readln(f, t);
SetLength(Data, Length(Data) + Length(t));
Data[z] := t;
until EOF(f);
SetLength(Data, Length(Data) + 3 * z);
//Add to each line the line number
for i := 1 to z do Data[i] := IntToStr(i) + ' ' + Data[i];
SetLength(Data, Length(Data) + 2);
//Add a carriage return and line feed
Data[1] := Data[1] + #13 + #10;
i := Length(Data[5]);
Data[5] := '';
SetLength(Data, Length(Data) - i);
//create a new textfile with the new data
AssignFile(f, OpenDialog1.FileName + '2');
ReWrite(f);
//write all lines
for i := 1 to z do writeln(f, Data[i]);
//save file and close it
CloseFile(f);
end;
end;