日期:2014-05-17  浏览次数:20601 次

如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据

如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据?

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) . "<br/>";
}
}else{
echo 'no';
}

楼主可以看看  
------其他解决方案--------------------
本帖最后由 xuzuning 于 2012-11-21 12:46:50 编辑
$n = 3;//取3行
$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);
Array
(
    [0] => cccccccc
    [1] => dddddddd
    [2] => eeeeeeee
)

------其他解决方案--------------------
 "\r"://是行尾
#echo "-->>4<br>";
      if($t) {  #这里是否是判断$n为真?
        array_unshift($res, $t);//保存缓冲区
        echo "res-->>";print_r($res);echo "<br>";
        $n--;
      }
      $t = '';
      break;
    default:
#echo "-->>5<br>";
      $t = $ch . $t;//缓存字符  #这里的$t和最终结果有什么关系?
  }
  fseek($fp, -2, SEEK_CUR);//向前跳2的字符
}
return $res;
}

------其他解决方案--------------------
读取的话应该可以按照行来读取的 楼主可以找下资料
------其他解决方案--------------------
将文件的指针移动到你要开始读取的位置(利用fseek()函数),然后读取文件。
------其他解决方案--------------------