Ecco la mia soluzione per la stampa del file all'indietro. È piuttosto compatibile con la memoria. E sembra più leggibile (IMO [= a mio parere]).
Passa attraverso il file all'indietro, conta i caratteri fino all'inizio di una riga o all'inizio del file e quindi legge e stampa quella quantità di caratteri come una linea, quindi sposta il cursore indietro e legge un'altra riga come quella ...
if($v = @fopen("PATH_TO_YOUR_FILE", 'r')){ //open the file
fseek($v, 0, SEEK_END); //move cursor to the end of the file
/* help functions: */
//moves cursor one step back if can - returns true, if can't - returns false
function moveOneStepBack(&$f){
if(ftell($f) > 0){ fseek($f, -1, SEEK_CUR); return true; }
else return false;
}
//reads $length chars but moves cursor back where it was before reading
function readNotSeek(&$f, $length){
$r = fread($f, $length);
fseek($f, -$length, SEEK_CUR);
return $r;
}
/* THE READING+PRINTING ITSELF: */
while(ftell($v) > 0){ //while there is at least 1 character to read
$newLine = false;
$charCounter = 0;
//line counting
while(!$newLine && moveOneStepBack($v)){ //not start of a line/the file
if(readNotSeek($v, 1) == "\n") $newLine = true;
$charCounter++;
}
//line reading/printing
if($charCounter>1){ //if there was anything on the line
if(!$newLine) echo "\n"; //prints missing "\n" before last *printed* line
echo readNotSeek($v, $charCounter); //prints current line
}
}
fclose($v); //close the file, because we are well-behaved
}
Naturalmente sostituire PATH_TO_YOUR_FILE
con il proprio percorso al file, @
viene utilizzato quando si apre il file, perché quando il file non si trova o non può essere aperto - viene sollevato avvertimento - se si desidera visualizzare questo avviso - basta rimuovere il surpressore di errore '@'.
fonte
2014-10-27 19:15:30
modo 'a +' sposta il cursore alla fine del file per voi :) (ma c'è un bug che il cursore viene spostato dopo il primo I/O, non immediatamente) –