如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据
$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);
print_r(invertedReadFile('menu.txt', 3));Array
function invertedReadFile($filename,$n=20){
$fp = fopen($filename, 'r');//打开文件
if (!$fp) return false;
fseek($fp, -1, SEEK_END);//跳到最后一个字节出
$res = array();//初始化结果数组
$t = '';//初始化缓冲区
while($n && $ch = fgetc($fp)) {//循环读取
switch($ch) {
case "\n":
case "\r"://是行尾
if($t) { #这里是否是判断$n为真?
array_unshift($res, $t);//保存缓冲区
$n--;
}
$t = '';
break;
default:
$t = $ch . $t;//缓存字符 #这里的$t和最终结果有什么关系?
}
fseek($fp, -2, SEEK_CUR);//向前跳2的字符
}
return $res;
}