Author: Lou Adler How to rewrite the last line of text in a text file Answer: 1 2 procedure RewriteLastTextLine(AFileName: string; ANewTextLine: string); 3 const 4 BUFFER_SIZE = 1024; {change this number for different sized buffer} 5 CRLF = #13#10; 6 var 7 fs: TFileStream; 8 buf: PChar; 9 iStartWritePos: Int64; 10 11 function AssignPos: Boolean; 12 var 13 i: Integer; 14 begin 15 for i := BUFFER_SIZE - 1 downto 0 do 16 if (buf[i] = #13) then 17 begin 18 iStartWritePos := (iStartWritePos - (BUFFER_SIZE - i)); 19 Result := True; 20 Exit; 21 end; 22 Result := False; 23 end; 24 25 procedure ReadABuffer; 26 begin 27 fs.Position := fs.Position - BUFFER_SIZE; 28 fs.read(buf^, BUFFER_SIZE); 29 fs.Position := fs.Position - BUFFER_SIZE; 30 end; 31 32 begin 33 fs := TFileStream.Create(AFileName, fmOpenReadWrite or fmShareDenyWrite); 34 try 35 GetMem(buf, BUFFER_SIZE); 36 FillMemory(buf, BUFFER_SIZE, 0); 37 fs.Position := fs.Size; 38 iStartWritePos := fs.Position; 39 repeat 40 ReadABuffer 41 until 42 AssignPos; 43 fs.Position := iStartWritePos; 44 fs.write(CRLF, Length(CRLF)); 45 fs.write(ANewTextLine[1], Length(ANewTextLine)); 46 finally 47 FreeMem(buf, BUFFER_SIZE); 48 fs.Free; 49 end; 50 end;