使用fseek逐行读取文件 [英] Read a file backwards line by line using fseek

查看:139
本文介绍了使用fseek逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用fseek逐行读取文件?

How do I read a file backwards line by line using fseek?

代码可能会有所帮助.必须是跨平台和纯PHP.

code can be helpful. must be cross platform and pure php.

非常感谢

致谢

杰拉

推荐答案

问题是使用fseek提出的,因此只能假定性能是问题,而file()不是解决方案.这是使用fseek的简单方法:

The question is asking using fseek, so can only assume that performance is an issue and file() is not the solution. Here is a simple approach using fseek:

我的file.txt

My file.txt

#file.txt
Line 1
Line 2
Line 3
Line 4
Line 5

和代码:

<?php

$fp = fopen('file.txt', 'r');

$pos = -2; // Skip final new line character (Set to -1 if not present)

$lines = array();
$currentLine = '';

while (-1 !== fseek($fp, $pos, SEEK_END)) {
    $char = fgetc($fp);
    if (PHP_EOL == $char) {
            $lines[] = $currentLine;
            $currentLine = '';
    } else {
            $currentLine = $char . $currentLine;
    }
    $pos--;
}

$lines[] = $currentLine; // Grab final line

var_dump($lines);

输出:

array(5) {
   [0]=>
   string(6) "Line 5"
   [1]=>
   string(6) "Line 4"
   [2]=>
   string(6) "Line 3"
   [3]=>
   string(6) "Line 2"
   [4]=>
   string(6) "Line 1"
}

您不必像我一样附加到$ lines数组,如果这是脚本的目的,则可以立即打印输出.如果要限制行数,也很容易引入计数器.

You don't have to append to the $lines array like I am, you can print the output straight away if that is the purpose of your script. Also it is easy to introduce a counter if you want to limit the number of lines.

$linesToShow = 3;
$counter = 0;
while ($counter <= $linesToShow && -1 !== fseek($fp, $pos, SEEK_END)) {
   // Rest of code from example. After $lines[] = $currentLine; add:
   $counter++;
}

这篇关于使用fseek逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆