Mega Code Archive

 
Categories / Delphi / Examples
 

Read a text file backwards

To read a text file backwards, you have to open it as a binary file, e.g. with FileOpen(). The following procedure ReadBack() reads one line backwards - up to the current position -. So, initially, you need to position to the end of the file. The usage is demonstrated in the routine FormCreate() below: procedure Readback (const f: integer; var Line: String; var _bof: boolean); const MAXLINELENGTH = 256; var curr, Before : Longint; Buffer : array [0..MAXLINELENGTH] of char; p : PChar; begin // scan backwards to the last CR-LF curr := FileSeek (f, 0, 1); Before := curr - MAXLINELENGTH; if Before < 0 then Before := 0; FileSeek (f, Before, 0); FileRead (f, Buffer, curr - Before); Buffer[curr - Before] := #0; p := StrRScan (Buffer, #10); if p = Nil then begin Line := StrPas (Buffer); FileSeek (f, 0, 0); _bof := True end else begin Line := StrPas (p + 1); FileSeek (f, Before + Longint (p) - Longint (@Buffer), 0); _bof := False end; // this will also work with Unix files (#10 only, no #13) if length (Line) > 0 then if Line[length (Line)] = #13 then begin SetLength (Line, length (Line) - 1) end end; procedure TForm1.FormCreate (Sender: TObject); const FileName = 'c:\delphi3\bin\unit1.pas'; var f : integer; Line : string; BeginOfFile : boolean; begin f := FileOpen (FileName, 0); // move to end of file! FileSeek (f, 0, 2); // read all lines, backwards repeat Readback (f, Line, BeginOfFile); ListBox1.Items.Insert (0, Line); until BeginOfFile; FileClose (f); end;