From ca7e5ec831cbd65c6c75d6e6ad64d1586fed56ee Mon Sep 17 00:00:00 2001 From: david Date: Sun, 5 Sep 2021 22:22:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9A=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E6=97=A5=E5=BF=97=E6=9C=80=E5=90=8EN?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/functions.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/app/functions.php b/app/functions.php index b269bf3..c4dd7e1 100644 --- a/app/functions.php +++ b/app/functions.php @@ -126,3 +126,41 @@ function dataSize($bytes, string $delimiter = '', int $decimals = 2):string return number_format($bytes, $decimals) . $delimiter . $type[$i]; } + +/** + * 工具函数,读取文件最后$n行 + * @param string $filename 文件的路径 + * @param int $n 文件的行数 + * @return string + */ +function fileLastLines(string $filename, int $n = 1) +{ + // 文件存在并打开文件 + if (!is_file($filename) || !$fp = fopen($filename, 'r')) { + return null; + } + + $pos = -2; + $eof = ''; + $lines = array(); + while ($n > 0) { + $str = ''; + while ($eof != "\n") { + //在打开的文件中定位 + if (!fseek($fp, $pos, SEEK_END)) { + //从文件指针中读取一个字符 + $eof = fgetc($fp); + $pos--; + $str = $eof . $str; + } else { + break; + } + } + // 插入到数组的开头 + array_unshift($lines, $str); + $eof = ''; + $n--; + } + + return implode('', $lines); +}