php模仿linux tail 命令读取文件最后几行

function tail($file , $num_to_get = 100) {
	$fp = fopen($file,'r');
	$position = filesize($file);
	fseek($fp, $position-1);
	$chunklen = 4096;
	//$line = fgets($fp);
	//var_dump($line);
	while ($position >= 0) {
		$position -= $chunklen;
		if($position < 0) {
			$chunklen = abs($position);
			$position = 0;
		}
		fseek($fp,$position);
		$data = fread($fp, $chunklen).$data;
		if (substr_count($data, "\n") >= $num_to_get + 1)
		{
			preg_match("!(.*?\n){".($num_to_get-1)."}$!", $data, $match);
			return $match[0];
		}
	}
	fclose($fp);
	return $data;
}


你可能感兴趣的:(php模仿linux tail 命令读取文件最后几行)