<?php

$start = microtime(TRUE);
$filesize = filesize('SHUIPING_YANG.log');
$fp = fopen('SHUIPING_YANG.log', 'r');
$getfp = fopen('SHUIPING_YANG.log', 'r');

$lines = 0;
$line = 0;

//获取文件的一行内容,注意:需要php5才支持该函数;
//第一种方法,可以设置定界符"\r \t \n",注意设置定界符的时候要用双引号!
while (stream_get_line($fp, $filesize,"\n")) {
    $line++;
}
fclose($fp); //关闭文件

while (fgets($getfp)) {
    $lines++;
}
fclose($getfp); //关闭文件

printf("stream_get_line函数所取得的文件行数为:%s", $line);
echo '<br>';
printf("fgets函数所取得的文件行数为:%s", $lines) ;

echo '<br>';
$end = microtime(TRUE);
echo '耗时' . $deltime = $end - $start;


//第二种方法
/*获取大文件最后N行方法
原理:
首先通过fseek找到文件的最后一位EOF,然后找最后一行的起始位置,取这一行的数据,再找次一行的起始位置, 再取这一行的位置,依次类推,直到找到了$num行。
 */

$file = "F:\access_log";
var_dump(tail($file, 10));

function tail($file, $num) {
    $fp = fopen($file, "r");
    $pos = -2;
    $eof = "";
    $head = false; //当总行数小于Num时,判断是否到第一行了
    $lines = array();
    while ($num > 0) {
        while ($eof != "\n") {
            if (fseek($fp, $pos, SEEK_END) == 0) {
                //fseek成功返回0,失败返回-1
                $eof = fgetc($fp);
                $pos--;
            } else {
                //当到达第一行,行首时,设置$pos失败
                fseek($fp, 0, SEEK_SET);
                $head = true; //到达文件头部,开关打开
                break;
            }
        }
        array_unshift($lines, fgets($fp));
        if ($head) {break;} //这一句,只能放上一句后,因为到文件头后,把第一行读取出来再跳出整个循环
        $eof = "";
        $num--;
    }
    fclose($fp);
    return $lines;
}
?>
所有评论
加载评论 ...
发表评论