PHP
·
发表于 5年以前
·
阅读量:8309
ͨ³£À´ËµÔÚphp¶ÁÈ¡´oÎļþµÄʱºo£¬ÎÒÃDzÉÓõĽ¨Ò»°aÊÇÒ»ÐÐÐÐÀ´½²È¡£¬¶ø²»ÊÇÒ»´ÎÐÔ°ÑÎļþÈ«²¿Ð´ÈeÄÚ´aeÖУ¬ÕaÑu»aµ¼ÖÂphp³ÌÐo¿¨ËÀ£¬ÏÂÃae¾Í¸ø´o¼Ò½eÉÜÕaÑuÒ»¸oÀý×Ó¡£
¶ÁÈ¡´oÎļþ×iºo¼¸ÐÐÊý¾Ý£º
<?php
/**
* È¡Îļþ×iºo$nÐÐ
*
* @param string $filename ÎļþÂ*¾¶
* @param int $n ×iºo¼¸ÐÐ
* @return mixed false±iʾÓдiÎo£¬³É¹¦Ôo*µ»Ø×Ö*u´®
*/
function FileLastLines($filename, $n){
if(!$fp = fopen($filename, 'r')){
echo "´o¿ªÎļþʧ°Ü£¬Çe¼i²eÎļþÂ*¾¶ÊÇ*ñÕýÈ*£¬Â*¾¶ºÍÎļþÃu²»Òª°uº¬ÖÐÎÄ";
return false;
}
$pos = -2;
$eof = "";
$str = "";
while($n > 0){
while($eof != "n"){
if(!fseek($fp, $pos, SEEK_END)){
$eof = fgetc($fp);
$pos¨C;
}else{
break;
}
}
$str .= fgets($fp);
$eof = "";
$n¨C;
}
return $str;
}
echo nl2br(FileLastLines('sss.txt', 4));
/**
* * * È¡Îļþ×iºo$nÐÐ *
*
* @param string $filename ÎļþÂ*¾¶ *
* @param int $n ×iºo¼¸ÐÐ *
* @return mixed false±iʾÓдiÎo£¬³É¹¦Ôo*µ»Ø×Ö*u´®
*/
function FileLastLines($filename, $n){
if(!$fp = fopen($filename, 'r')){
echo "´o¿ªÎļþʧ°Ü£¬Çe¼i²eÎļþÂ*¾¶ÊÇ*ñÕýÈ*£¬Â*¾¶ºÍÎļþÃu²»Òª°uº¬ÖÐÎÄ";
return false;
}
$pos = -2;
$eof = "";
$str = "";
while($n > 0){
while($eof != "n"){
if(!fseek($fp, $pos, SEEK_END)){
$eof = fgetc($fp);
$pos--;
}else{
break;
}
}
$str .= fgets($fp);
$eof = "";
$n--;
}
return $str;
}
echo nl2br(FileLastLines('sss . txt', 4));
function tail($fp, $n, $base = 5)
{
assert($n > 0);
$pos = $n + 1;
$lines = array();
while(count($lines) < = $n){
try{
fseek($fp, - $pos, SEEK_END);
}
catch (Exception $e){
fseek(0);
break;
}
$pos *= $base;
while(!feof($fp)){
array_unshift($lines, fgets($fp));
}
}
return array_slice($lines, 0, $n);
}
var_dump(tail(fopen("access.log", "r+"), 10));
$fp = fopen($file, "r");
$line = 10;
$pos = -2;
$t = " ";
$data = "";
while ($line > 0){
while ($t != "n"){
fseek($fp, $pos, SEEK_END);
$t = fgetc($fp);
$pos --;
}
$t = " ";
$data .= fgets($fp);
$line --;
}
fclose ($fp);
echo $data;
?>
¶ÁÕß¿ÉÒÔ¸u¾Ý¸ÃʵÀýÌصa¼ÓÒԸĽøºÍÍeÉÆ£¬Ê¹Ö®¸u¼Ó*uºÏ×ÔÉiÓ¦ÓÃÐeÇo¡£