Archive for the ‘Sample Code’ Category

Count your LOC!!

How many Lines of Code(LOC), have you produced? For those wondering, how many lines of code have they generated, here is a sample code in C#.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace LOC
{
class Loc
{
private const string fileExtension = ".cs";

private static void Main(string[] args)
{
string path = "";
if (args.Length == 0)
{
//PrintUsageAndExit();
Console.WriteLine("Enter the path of the root folder containing the source code" + Environment.NewLine);
path = Console.ReadLine();
}
else
{
path = args[0];
}

if (string.IsNullOrEmpty(path) || !Directory.Exists(path))
{
PrintUsageAndExit();
}

DirectoryInfo parent = new DirectoryInfo(path);

int lines = CountLines(parent);
Console.WriteLine("The Total Number of Lines is :" + lines);
Console.ReadLine();
}

private static void PrintUsageAndExit()
{
Console.WriteLine("Expecting the path of a Directory containing Files or Sub Folders with file extension as " + fileExtension);

Console.WriteLine(Environment.NewLine + "Press any key to exit...");
Console.ReadLine();
Environment.Exit(1);
}

private static int CountLines(DirectoryInfo dir)
{
int lines = 0;
//process all the files in the directory
foreach (FileInfo f in dir.GetFiles())
{
//process only the files with the required file extension
if (f.Name.EndsWith(fileExtension))
{
lines += CountLines(f);
}

}

//process all the sub directories in the current directory
DirectoryInfo[] children = dir.GetDirectories();
foreach (DirectoryInfo d in children)
{
lines += CountLines(d);
}
return lines;
}

private static int CountLines(FileInfo file)
{
StreamReader reader = null;
int lines = 0;
try
{
reader = new StreamReader(file.FullName);

while (!reader.EndOfStream)
{
string line = reader.ReadLine().Trim();

//ignore blank lines and comments...TODO: Also ignore commented code with in /* ... */
if (string.IsNullOrEmpty(line) || line.StartsWith("//"))
{
continue;
}
lines++;
}
}
catch { }
finally
{
if (reader != null)
{ reader.Close(); }
}
return lines;
}
}
}

Advertisements