[fpc-pascal] read lines at end of file

José Mejuto joshyfun at gmail.com
Tue Apr 12 09:48:06 CEST 2011

Hello FPC-Pascal,

Tuesday, April 12, 2011, 12:51:17 AM, you wrote:

jgc> So the idea is to open file eg as file of array [1:65536] of char or
jgc> something similar, seek & read to end of file, then go through the last
jgc> array converting to strings by finding crlfs correct? Is this the simplest
jgc> way? If not any outline code?

There is the right way which is a bit complex as there are 3 different
line ending sequences based in the platform. The code get simpler if
you support only one end of line, but as in your case you only need 4
lines and this lines for sure are not too large there is a more simple
way, not very elegant but simple:

function GetLast4Lines(const aFileName: ansistring): ansistring;
  Lines: TStringList;
  FileToRead: TFileStream;
  Buffer: ansistring;
  ToReadBytes: int64;
  i: integer;
  //Open the file with fmShareDenyNone, so other process can write in
  //the file while I'm reading
  FileToRead := TFileStream.Create(aFileName,fmOpenRead or fmShareDenyNone);
  //Can I read at least 4096 bytes ?
  if FileToRead.Size > 4096 then ToReadBytes := 4096 else ToReadBytes := FileToRead.Size;
  //Locate read position at 4096 bytes from the end
  FileToRead.Position := FileToRead.Size - ToReadBytes;
  //Setup buffer to space needed
  SetLength (Buffer, ToReadBytes);
  //Read the last 4096 or less bytes in Buffer
  FileToRead.Read (Buffer[1], ToReadBytes);
  //Release the file, not needed anymore.
  //Create a lines array
  Lines := TStringList.Create;
  //Assign the buffer to the lines array
  Lines.Text := Buffer;
  //Initialize output to nothing
  //Read from lastline-4 to lastline
  for i := Lines.Count-1-4 to Lines.Count-1 do
    //Add each line to the output
    Result := Result + Lines[i] + LineEnding;
  //Release lines array
  //Result now have the last 4 files.

Best regards,

More information about the fpc-pascal mailing list