Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read single line from a big text file

Tags:

php

I have a 10MB text file.
The length of the lines may vary.

Which is the most efficient way (fast and memory friendly) to read just one specific line from this file? e.g. get_me_the_line($nr, $file_resource)

like image 457
Sfisioza Avatar asked Jan 26 '26 05:01

Sfisioza


2 Answers

I don't know of a way to just jump to the line, if the lines are of varying length. However you can iterate through lines pretty quickly when not using them for anything, and return the one of interest.

function ReadLineNumber($file, $number)
{
    $handle = fopen($file, "r");
    $i = 0;
    while (fgets($handle) && $i < $number - 1)
        $i++;
    return fgets($handle);
}

Edit

I added - 1 to the loop because this reads a line ahead. The $number is therefore a zero-index line reference. Change to - 2 if you would prefer line 1 mean the first line in the file.

like image 58
JYelton Avatar answered Jan 28 '26 20:01

JYelton


As the lines are of varying length you have to look at each character as it might denote the end of the line. Quickest would be loading the file in chunks that are sized like the blocksize of the filesystem and counting the linebreaks until you are on the desired line. Better way would be to have an index file that stores information about the file containing the lines. Using a database could also be a better idea.

like image 22
Nobody moving away from SE Avatar answered Jan 28 '26 18:01

Nobody moving away from SE