Fgets progress - an easier way?

I read a large ~ 500 MB text file and want to get progress during my read operations.

To do this, I now count the lines that the files have, and then compare them with the ones I already read. This requires two complete iterations over the file. Is there an easier way to use file size and flags?

My current code is as follows:

$lineTotal = 0;
while ((fgets($handle)) !== false) {
    $lineTotal++;
}

rewind($handle);

$linesDone = 0;
while (($line = fgets($handle)) !== false) {
    progressBar($linesDone += 1, $lineTotal);
}
+4
source share
1 answer

Based on bytes, not strings, but you can quickly get the total file size with filesize:

$bytesTotal = filesize("input.txt")

Then, after you have opened the file, you can read each line and then get the current position in the file, something like:

progressBar(0, $bytesTotal);
while (($line = fgets($handle)) !== false) {
    doSomethingWith($line, 'presumably');
    progressBar(ftell($handle), $bytesTotal);
}

, PHP 2G, , 500 , .

+1

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


All Articles