How to get the total number of lines before reading in a large file in PHP

I already use this example of how to read large data files in PHP in turn

Now, what he would like to do is get the total number of lines in the file, so that I can display the percentage filling, or at least what the total number of lines is, so I can give some idea of ​​how much processing should be done.

Is there a way to get the total number of lines without reading the entire file twice? (once for counting rows and once for processing)

+3
source share
5 answers

Poor men respond:

, . ( 250 ) .

estNumOfLines = sizeOfFile / avgLineSize

...

KB, .

+12

, , :

$fname = 'foofile.txt';
$fsize = filesize($fname);
$count = 0;
$handle = fopen($fname, "r") or die("Couldn't get handle");
if ($handle) {
  while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    // Process buffer here..
    $count++;
    echo ($count * 4096)/$fsize . " percent read.";
  }
  fclose($handle);
}

: ,

+5

- , , ? , , " ", / .

+3

linux wc -l filename.txt. .

+2

, ? .

Same thing, calculate the average line length from the first few lines, then do the same math with the file size ...

+1
source

Source: https://habr.com/ru/post/1706479/


All Articles