Search code examples
phpwindowsnumbersexeclines

Count lines of file in PHP on Windows


To determine the exact number of lines in a file I currently use:

if(exec("wc -l ".escapeshellarg($strFile), $arResult)) {
     $arNum = explode(" ", $arResult[0]);
     // ...
  }

What is the best way of doing the same on Windows?


Edit:

One attempt from another question:

$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}

fclose($handle);

echo $linecount;
  1. Has anyone got experience with this way using big files?

  2. Is there a way of using Windows commands to determine file size other then PHP functions?


Solution

I go with command find as recommended by the accepted answer in the comments.


Solution

  • I prefer to just loop through the file, reading a line each time and incrementing a counter, using and counting the array returned by file() is only good for smaller files.

    <?php
    
    $loc = 'Ubuntu - 10.10 i386.iso';
    
    $f = fopen($loc,'r');
    $count = 0;
    
    while (fgets($f)) $count++;
    
    fclose($f);
    
    print "Our file has $count lines" . PHP_EOL;
    

    if you'd use file() for a such a large file it would read it completely into memory, which can be prohibitive depending on your situation. If this is a 1-time "I don't care, it's my workstation and I have enough memory" situation or the files are guaranteed to be small then you could use

    count(file($loc));
    

    Otherwise I'd loop through, especially since if action would have to be performed by many processes. Both ways of counting loop through the whole of the file but memory increases vastly in the second case.