How to read only 5 last line of the text file in PHP?

前端 未结 18 1620
陌清茗
陌清茗 2020-11-28 08:45

I have a file named file.txt which is update by adding lines to it.

I am reading it by this code:

$fp = fopen(\"file.txt\", \"r\");
$da         


        
18条回答
  •  离开以前
    2020-11-28 09:19

    This is a common interview question. Here's what I wrote last year when I was asked this question. Remember that code you get on Stack Overflow is licensed with the Creative Commons Share-Alike with attribution required.

    = $numLines? $c-$numLines: 0;
    for (; $i<$c; ++$i) {
      if ($pos = strpos($lines[$i], $searchString)) {
        echo $lines[$i];
      }
    }
    

    This solution does make an assumption about the maximum line length. The interviewer asked me how I would solve the problem if I couldn't make that assumption, and had to accommodate lines that were potentially longer than any max length I chose.

    I told him that any software project has to make certain assumptions, but I could test if $c was less than the desired number of lines, and if it isn't, fseek() back further incrementally (doubling each time) until we do get enough lines.

提交回复
热议问题