Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading large files from end

Tags:

php

file-io

Can I read a file in PHP from my end, for example if I want to read last 10-20 lines?

And, as I read, if the size of the file is more than 10mbs I start getting errors.

How can I prevent this error?

For reading a normal file, we use the code :

if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
    $i1++;
    $content[$i1]=$buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

My file might go over 10mbs, but I just need to read the last few lines. How do I do it?

Thanks

like image 907
kritya Avatar asked Jun 23 '11 08:06

kritya


People also ask

How can I read a very large file?

The best way to view extremely large text files is to use… a text editor. Not just any text editor, but the tools meant for writing code. Such apps can usually handle large files without a hitch and are free. Large Text File Viewer is probably the simplest of these applications.

How can you read last 10 lines of a big file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How do I read a 100 GB file in Python?

Read large text files in Python using iterateThe input() method of fileinput module can be used to read large files. This method takes a list of filenames and if no parameter is passed it accepts input from the stdin, and returns an iterator that returns individual lines from the text file being scanned.


1 Answers

You can use fopen and fseek to navigate in file backwards from end. For example

$fp = @fopen($file, "r");
$pos = -2;
while (fgetc($fp) != "\n") {
    fseek($fp, $pos, SEEK_END);
    $pos = $pos - 1;
}
$lastline = fgets($fp);
like image 89
Greenisha Avatar answered Oct 26 '22 13:10

Greenisha