Click to See Complete Forum and Search --> : Recursive Line Counter


MikeSnead
04-21-2005, 07:45 PM
I recently completed a Senior Design project and was asked by a grading professor to give him a lines of code count. I had time so I wrote this little bit of code to do it. The professor counts a "line" as any line that ends with a semicolon and wanted only the php and javascript files counted.

Let me know what you think of the design and if it could be tweeked and/or otherwise fiddled with.


<?php

// WOWBAGGER LINE COUNT //

function count_directory ( $directory )
{
$directory_stream = opendir($directory) or die("cannot open directory ($directory)!");
$total_count = 0;

while ( !(($file = readdir($directory_stream)) === false ) )
{
if ( is_dir("$directory/$file") && $file != ".." && $file != "." )
{
$total_count += count_directory("$directory/$file");
}
else if ( !is_dir("$directory/$file") && is_countable($file) )
{
$total_count += count_lines($file,$directory);
}
}

return $total_count;
}

function count_lines ( $file , $directory )
{
$lines = file("$directory/$file");
$total = count($lines);
$count = 0;

for ( $i = 0 ; $i < $total ; $i++ )
{
$lines[$i] = rtrim($lines[$i]);
if ( substr($lines[$i],-1,1) == ";" )
{
$count++;
}
}

return $count;
//return count(file("$directory/$file"));
}

function is_countable ( $file )
{
$extension = strtolower(array_pop(explode(".",$file)));
switch ($extension)
{
case "php" : return true;
case "js" : return true;

default : return false;
}
}

$directory = ($_GET['dir'] != NULL) ? $_GET['dir'] : ".";

print "Directory \"$directory\" contains " . count_directory($directory) . " total lines.<br><br>";

?>


Note: It defaults to the current directory, but you can also give it a specific sub directory if you'd like.

mtmosier
04-25-2005, 02:10 AM
$ find . -follow -name "*.php" -print0 -or -name "*.js" -print0 | xargs -0 egrep ";[[:space:]]*$" | wc -l
2502
$ php count.php
Directory "." contains 2502 total lines.<br><br>

Of course I imagine writing the php was more exiciting.

MikeSnead
04-25-2005, 03:07 AM
Originally posted by mtmosier
Of course I imagine writing the php was more exiciting.

Well yeah... :p

bubblenut
05-30-2005, 11:29 AM
I always get worried about the use of file without first checking the size of the file. It's going to be fine for most situations but what happens if your program comes accross a large text file? It loads the whole thing into memory, wasting resources. What happens when it comes accross a 2 or 3 Gig file? Crunch goes your server. I would suggest either checking the file size before opening it or using fopen and fgets instead. Also, your code breaks down if there are comments at the ends of line.

function countLines($file) {
if(!$fp = fopen($file, 'r')) {
return 0;
} else {
$count = 0;
while(!feof($fp)) {
$line = fgets($fp, 16384);
if(preg_match(';\s*(//.*|/\*.*)$|', $line)
$count++;
}
return $count;
}
}