如何在不讀取全部檔案內容的前提下倒序取出檔案的最後幾條資料
如何在不讀取全部檔案內容的前提下倒序取出檔案的最後幾條資料?
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';
}
樓主可以看看
------解決方案--------------------
本帖最後由 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
)
------解決方案--------------------
print_r(invertedReadFile('menu.txt', 3));
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 = '';