$file = new SplFileObject('/path/to/file.txt');
How can I find the number of lines in a file with SplFileObject
?
iterator_count
and line-by-line iterating using next()
is broken in my php version 5.3.7 under Ubuntu.
Also seems broken fseek([any offset], SEEK_END)
method. key()
returns 0.
Iterate over large files using seek($lineCount)
is too slow.
Simpliest 5.3.7-verified way is
// force to seek to last line, won't raise error
$file->seek($file->getSize());
$linesTotal = $file->key();
Counting 30000 lines requires now 0.00002 secs and costs about 20 kb of memory.
Iterations method takes about 3 seconds.
I agree with Николай Конев on using seek function
is much faster than going through the entire file line by line, but as Twisted1919 said using the file size to seek the last line is confusing so my suggestion is use PHP_INT_MAX instead of the file size:
// force to seek to last line, won't raise error
$file->seek(PHP_INT_MAX);
$linesTotal = $file->key();
The SplFileObject
offers an itertor, one iteration per line:
$numberOfLines = iterator_count($file);
The function iterator_count
is your friend here, doing the traversal for you and returning the number of iterations.
You can make use of the file object's SKIP_EMPTY
flag to not count empty lines in that file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With