Home  >  Article  >  Backend Development  >  怎么在不读取全部文件内容的前提下倒序取出文件的最后几条数据

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

WBOY
WBOYOriginal
2016-06-13 12:51:00803browse

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

<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 />

------解决方案--------------------
$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 />
}

楼主可以看看  
------解决方案--------------------

本帖最后由 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);
Array
(
    [0] => cccccccc
    [1] => dddddddd
    [2] => eeeeeeee
)

------解决方案--------------------
print_r(invertedReadFile('menu.txt', 3));<br>
<br>
function invertedReadFile($filename,$n=20){<br>
    $fp = fopen($filename, 'r');//打开文件<br>
    if (!$fp) return false;<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) {  #这里是否是判断$n为真?<br>
            array_unshift($res, $t);//保存缓冲区<br>
            $n--;<br>
          }<br>
          $t = ''; <div class="clear">
                 
              
              
        
            </div>
Statement:
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
Previous article: PHP停解析swf文件头 Next article: linux停zend framework