Programming C# C++ (7) Delphi (618) .NET (2) Database (71) Delphi IDE (90) Network (39) Printing (3) Strings (12) VCL (83) Windows with Delphi (280) Java (8) JavaScript (30) perl (9) php (4) VBScript (1) Visual Basic (1)
Exchange Links About this site Links to us 
|
Read a text file backwards
4 comments. Current rating: (4 votes). Leave comments and/ or rate it.
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
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;
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);
FileSeek (f, 0, 2);
repeat
Readback (f, Line, BeginOfFile);
ListBox1.Items.Insert (0, Line);
until BeginOfFile;
FileClose (f);
end; | |  | |  |
Comments:
2007-08-17, 06:01:52 (updated: 2007-08-17, 06:02:55) |
|
|
|
|
|
|
|
|
great !!
|
|
|
|
|
Wow!!! Good job. Could I take some of yours triks to build my own site?f
|
|
|
|
|
Many interesting information on your site - keep up good works
|
|