怎麼在不讀取全部檔案內容的前提下倒序取出檔案的最後幾條資料

來源:互聯網
上載者:User
如何在不讀取全部檔案內容的前提下倒序取出檔案的最後幾條資料

如何在不讀取全部檔案內容的前提下倒序取出檔案的最後幾條資料?

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 = '';
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.