Proposed solution below.
I'm fairly new to PHP and very new to OO so please forgive/Point out any
issues/problems
<?php
/************************************************** ***
** Title.........: RevFile Class
** Version.......: 1.00
** Author........: Steve Weet <sw***@weet.demon.co.uk>
** Filename......: class.RevFile.php
** Last changed..: 30th Jan 2004
** Purpose.......: Allows the display of a file in
** ..............: In reverse order
************************************************** ****/
// Example Usage
$file = new RevFile("/etc/passwd");
while ( ! $file->sof() ) {
echo $file->GetLine() ;
}
class RevFile {
var $FileName;
var $FileHandle;
var $FilePos;
function RevFile($filename) {
$this->FileName = $filename;
$this->FileHandle = @fopen($filename, "r") or
die("Could not open file $filename\n");
// Find EOF
if ( ! (fseek($this->FileHandle, 0, SEEK_END ) == 0 ))
die ("Could not find end of file in $filename\n");
// Store file position
$this->FilePos = ftell($this->FileHandle);
// Check that file is not empty or doesn;t contain a single newline
if ($this->FilePos < 2 )
die ("File is empty\n");
// Position file pointer just before final newline
// i.e. Skip EOF
$this->FilePos -= 1;
}
function GetLine() {
$pos = $this->FilePos -1;
$ch=" ";
$line = "";
while ($ch != "\n" && $pos >= 0) {
fseek($this->FileHandle, $pos );
$ch = fgetc($this->FileHandle);
// Decrement out pointer and prepend to the line
// if we have not hit the new line
if ( $ch != "\n" ) {
$pos = $pos -1;
$line = $ch . $line;
}
}
$this->FilePos = $pos ;
return $line . "\n";
}
function sof() {
return ($this->FilePos <= 0 );
}
}
?>
Erik Andersson wrote:
Hi!
I need to read a file (line-by-line) in reverse order, without reading the
whole file into memory first.
Is there an easy way of doing this? As in, is there a PHP function I could
use?
The solution has to be platform independent, so "popen("tac $filename")...
wouldn't work.
Example input and ouput:
<myfile.txt input>
line 1
line 2
line 3
</myfile.txt input>
<output from php script>
line 3
line 2
line 1
</output from php script>
All the best,
Erik
--
Erik Andersson ( AussieTraders.com.au )
http://www.aussietraders.com.au/
- Placing an add is FREE at AussieTraders.com.au, Australia's buy & sell
marketplace