时间:2021-07-01 10:21:17 帮助过:19人阅读
如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据?
Demo:
Filename:menu.txt
Content:
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
eeeeeeee
Result:(取出最后3条)
$res = array(
array("eeeeeeee"),
array("dddddddd"),
array("cccccccc"),
);
$filename = "menu.txt";//文件名
$handle = fopen( $filename, "rb" );
if( fseek( $handle, 0, SEEK_END ) !== -1 ){//指向文件尾
$k = 3;//获取的条数
$s = 0;
while( $k-- ){
if ( fseek( $handle, $s-1, SEEK_END ) === -1 ) break;//指针向前移动一个位置
while( fgetc($handle)!="\n" ){
--$s;
fseek( $handle, $s, SEEK_END );
}
fseek( $handle, $s+1, SEEK_END );//指针后移一位
echo fgets($handle) . "
";
}
}else{
echo 'no';
}
$n = 3;//取3行Array
$fp = fopen('menu.txt', 'r');//打开文件
fseek($fp, -1, SEEK_END);//跳到最后一个字节出
$res = array();//初始化结果数组
$t = '';//初始化缓冲区
while($n && $ch = fgetc($fp)) {//循环读取
switch($ch) {
case "\n":
case "\r"://是行尾
if($t) {
array_unshift($res, $t);//保存缓冲区
$n--;
}
$t = '';
break;
default:
$t = $ch . $t;//缓存字符
}
fseek($fp, -2, SEEK_CUR);//向前跳2的字符
}
print_r($res);