加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[PHP] 使用ftell和fseek函数直接定位文件位置获取部分数据

发布时间:2021-05-21 06:50:48 所属栏目:大数据 来源: https://www.jb51.cc
导读:? 对于大文件只获取部分数据很有用 1.使用ftell函数可以获取当前指针的字节位置 2.使用fseek函数可以直接定位到指定的位置 3.读取指定字节的数据就可以部分获取文件内容了 ? PHP class FileStream{ private $fp = null ; $mode = 'r' $context = $readonly =

?

对于大文件只获取部分数据很有用

1.使用ftell函数可以获取当前指针的字节位置
2.使用fseek函数可以直接定位到指定的位置
3.读取指定字节的数据就可以部分获取文件内容了

<?PHP
class FileStream
{
    private $fp = null;
    $mode = 'r'$context = $readonly = false$writeonly = $appendMode = ;

    public function __construct($file,$mode = 'r',1)">)
    {
        $mode = trim($mode);
        if (isset($mode[0])) {
            $this->mode = strtolower();
        }

        if ($context) {
            $this->context = ;
            $this->fp = fopen($mode,false,1)">$this->context);
        } else {
            if (!fp) {
            throw new Exception('can not open ' . $file);
        }
        
        $this->mode == 'r'$this->readonly = true;
        } elseif ($this->mode == 'w'$this->writeonly = $this->mode[0] == 'a'$this->appendMode = ;
        }
    }

    function __destruct()
    {
        close();
    }

     close()
    {
        fclose(fp);
            function read($size)
    {
        writeonly) {
            Exception('write only'Exception('stream already closed');
        }

        $buf = fread($this->fp,1)">$buf === ) {
            Exception('read Failed'return $buf;
    }

     readLine()
    {
        );
        }
                
        return fgets(fp);
    }

     readAll()
    {
        $buf = '';

        while ($s = );
            $s === ) {
                );
            }

            if (!$s[0])) {
                break;
            }

            $buf .= $s;
        }

        function write($datareadonly) {
            Exception('read only'fwrite($data) === Exception('write Failed');
        }
    }
    
     tell()
    {
        appendMode) {
            Exception('tell can not work on appendmode'$p = ftell(fp);
        $p === Exception('tell Failed'$pfunction seek($positionException('seek can not work on seekmode'fseek($position) !== 0Exception('seek Failed');
        }
    }
}

$stream=new FileStream("1.log");
$start=0;
$end=0;
//获取开始和结束的字节位置
while($ln=$stream->readLine()){
    if($ln=="3333333333333rn"){
        $start=tell();
    }
    $ln=="5555555555555rn"){
       $end=tell();
    }
}
var_dump($start,1)">$end);

直接定位到开始的字节位置
$stream->seek($start);
读取指定字节数的数据
$res=$stream->read($end - $res);

1.log的内容

2.获取部分结果

?

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读