You have to read it in chunks of data. More or less like this:
$file = fopen("teste.txt",'r');
$count = 0;
while (!feof($file)) {
$line = fgets($file, 4096); //provavelmente eu colocaria um valor maior, jamais menor
$count++;
}
fclose($file);
I put a 4096 limit because it is risky if the file is too large and does not have enough line breaks to create small chunks . This solution is not perfect. A better one would need a much more sophisticated algorithm.
I came to think of another one that has problems too:
$file = fopen("teste.txt",'rb');
$count = 0;
while (!feof($file)) {
$chunk= fread($f, 4096); //provavelmente eu colocaria um valor maior, jamais menor
$count += substr_count($chunk, "\n");
}
fclose($file);
The line break can have more than one character and get one character in one chunk and the other in the next chunk . There you will not tell.
Ready-to-produce solutions would have to consider this and treat when it does. This is easier to solve in the second algorithm. It still has the advantage of never filling your memory.
Run tests to evaluate the best chunk size. I put 4K because it is the size of the memory page and the most common size of the cluster file system. Minors will be worse and tend to be more at risk of cutting line by half disrupting both algorithms. Larger ones can give much better results. I would venture to say that the higher the better, but it depends on the hardware, OS, usage pattern, etc. It can be good at testing and create some problem in use in production. If I could read the whole file it would always be the fastest and risk free.
GuilhermeLautert raised a question of% cos_de% being only the line feed and therefore would not cause problem in the break. But in Windows the break is \n
(I can not test). Of the two one or PHP considers the \r\n
in the code as a full line break and what I said happens, or this code would not work correctly in Windows, requiring the use of \n
in the code to get the break in the correct way , which would have the problem of splitting the line break indicator in the same way.