怎么在不读取全部文件内容的前提上倒序取出文件的最后几条数据

WBOY
Release: 2016-06-13 10:59:07
Original
852 people have browsed it

如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据

<br />如何在不读取全部文件内容的前提下倒序取出文件的最后几条数据?<br /><br />Demo:<br />Filename:menu.txt<br />Content:<br />aaaaaaaa<br />bbbbbbbb<br />cccccccc<br />dddddddd<br />eeeeeeee<br /><br />Result:(取出最后3条)<br />$res = array(<br />  array("eeeeeeee"),<br />  array("dddddddd"),<br />  array("cccccccc"),<br />);<br />
Copy after login

------最佳解决方案--------------------
$filename = "menu.txt";//文件名<br />$handle = fopen( $filename, "rb" );<br />if( fseek( $handle, 0, SEEK_END ) !== -1 ){//指向文件尾<br />	$k = 3;//获取的条数<br />	$s = 0;<br />	while( $k-- ){<br />		if ( fseek( $handle, $s-1, SEEK_END ) === -1 ) break;//指针向前移动一个位置<br />		while( fgetc($handle)!="\n" ){<br />			--$s;<br />			fseek( $handle, $s, SEEK_END );<br />		}<br />		fseek( $handle, $s+1, SEEK_END );//指针后移一位<br />		echo fgets($handle) . "<br/>";<br />	}<br />}else{<br />	echo 'no';<br />}
Copy after login

楼主可以看看
------其他解决方案--------------------
本帖最后由 xuzuning 于 2012-11-21 12:46:50 编辑
$n = 3;//取3行<br />$fp = fopen('menu.txt', 'r');//打开文件<br />fseek($fp, -1, SEEK_END);//跳到最后一个字节出<br />$res = array();//初始化结果数组<br />$t = '';//初始化缓冲区<br />while($n && $ch = fgetc($fp)) {//循环读取<br />  switch($ch) {<br />    case "\n":<br />    case "\r"://是行尾<br />      if($t) {<br />        array_unshift($res, $t);//保存缓冲区<br />        $n--;<br />      }<br />      $t = '';<br />      break;<br />    default:<br />      $t = $ch . $t;//缓存字符<br />  }<br />  fseek($fp, -2, SEEK_CUR);//向前跳2的字符<br />}<br />print_r($res);
Copy after login
Array
(
[0] => cccccccc
[1] => dddddddd
[2] => eeeeeeee
)

------其他解决方案--------------------
"\r"://是行尾
#echo "-->>4
";
if($t) { #这里是否是判断$n为真?
array_unshift($res, $t);//保存缓冲区
echo "res-->>";print_r($res);echo "
";
$n--;
}
$t = '';
break;
default:
#echo "-->>5
";
$t = $ch . $t;//缓存字符 #这里的$t和最终结果有什么关系?
}
fseek($fp, -2, SEEK_CUR);//向前跳2的字符
}
return $res;
}

------其他解决方案--------------------
读取的话应该可以按照行来读取的 楼主可以找下资料
------其他解决方案--------------------
将文件的指针移动到你要开始读取的位置(利用fseek()函数),然后读取文件。
------其他解决方案--------------------

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!