21,886
社区成员
发帖
与我相关
我的任务
分享
<?php
function getLatestLines($filename,$count = 20,$sep = "\r\n"){ // 注意这里必须用双引号
$content = ''; // 最终内容
$_current = '';// 当前读取内容寄存
$seper = '';// 分隔符判断
$seperLen = strlen($sep); // 分隔符长度
$step= 1; // 每次走多少字符
$pos = 0;// 起始位置 -1 就是从最后一个开始
$i = 0;
$count--;
$handle = fopen($filename,'a+'); //读写模式,指针会被放在最后 当然也可以探测出 filesize然后从最后往前读。
while($i < $count && fseek($handle,$pos,SEEK_END) ===0){
// SEEK_END - 设定位置为文件尾加上 offset 。(要移动到文件尾之前的位置,需要给 offset 传递一个负值。)
$_current = fread($handle,$step);
$seper = $_current.$seper;
if (strlen($seper)>$seperLen){
$seper = substr($seper, 0, -$seperLen); // 截取当前字符最后几位。与分隔符匹配,所以长度和分隔符要一样。
}
$content = $_current.$content;
$pos -= $step; // 向后退
if ($sep === $seper ){ // 判断是否是换行或其他分隔符
$i++;
}
}
fclose($handle);
return $content;
}
$filename = 'c:/logfile.log'; // 需要读取的文件 3.5G 文件已测试过。
$sep = "\r\n"; // 行分隔符 注意这里必须用双引号-_-#
$count = 20; // 读取行数 \r\n 读取3行以下有点问题
echo getLatestLines($filename,$count,$sep);
?>
$file_name = 'E:\test.txt';
$data = file_get_contents($file_name);
$content = ''; //输出内容
$line_count = 0; //行数计算
$LINE = 20; //需要截取的行数
$i = $data_len = strlen($data);
while ( $i-- > 0 && $line_count < $LINE ) {
$content = $content.$data{$i};
if ( $data{$i} == "\n" )
$line_count++;
}
echo strrev($content);
<?
$f = file("xxxxx.dat");
$count = count($f);
print_r(array_slice($f,$count-20,$count));
?>