Page 1 of 1

need a function to write the last 100 lines log reverse

Posted: Thu Nov 06, 2008 6:25 am
by susrisha
Hello all.
I have a log file that keeps on updating due to one of the programs i wrote. The issue is that i want to read the last 100 lines of log file in reverse order. Found some function in http://in.php.net/manual/en/function.fseek.php
This isnt helping. Here is my requirement in detail:

Input log file has :
Line1
Line2
Line3
Line4
LastLine
===end of input===

Now i need an output as

LastLine
Line4
Line3
==== if given the number of lines from end of file as 3===

Can someone suggest me for writing this code. I am low on knowledge about the functions to be used.
Please guide me.

Re: need a function to write the last 100 lines log reverse

Posted: Thu Nov 06, 2008 6:45 am
by Eran
You can read the file into an array and reverse the array - easy to do but this requires loading the entire file into memory, which could run you out of memory.

I use the following which will work on linux only -

Code: Select all

 
$file = popen("tac " . $file ,'r'); //Opens the file from the end
while ($line = fgets($file)) {
       //do what you want with each line
}
 

Re: need a function to write the last 100 lines log reverse

Posted: Thu Nov 06, 2008 7:03 am
by someberry
I would explode the data on new lines and then reverse the array.

Re: need a function to write the last 100 lines log reverse

Posted: Thu Nov 06, 2008 7:23 am
by susrisha
thanks alot for the code