Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Lines of Code Example

Part of StandardLibraryCategory

Description

This example counts the number of lines for each file that matches the filter in the specified folder.

To make it easier to implement, it counts comments (though it does try to exclude blank lines). I would only use this to get a rough idea of the complexity of various files. Learn more about the pros and cons of measuring lines of code at Wikipedia.

Example

import std.file;
import std.stdio;
import std.stream;
import std.string;
import std.regexp;


const char[] pgmName = "LinesOfCodeExample";

char[] outputData;


int main(char[][] args)
{
    char[] patternStr;
    char[] pathStr;
    char[] outputFileStr;

    if(args.length < 3)
    {
        writefln("Usage: " ~ pgmName ~ " pattern input_path output_file");
        return 0;
    }
    else
    {
        patternStr = args[1];
        pathStr = args[2];
        outputFileStr = args[3];
    }

    int n = listdirfn(pathStr, patternStr);

    writef("Number: %s\n", n);

    std.file.write(outputFileStr, cast(byte[])outputData);

    return 0;
}


int listdirfn(char[] pathname, char[] pattern)
{
    auto r = new RegExp(pattern, "i");
    int n;

    File fl;

    bool callback(DirEntry* de)
    {
        if (de.isdir)
            std.file.listdir(de.name, & callback);
        else
        {   if (r.test(de.name))
            {
                writefln("%s", de.name);
                n++;

                fl = new File(de.name);
                int cntLn = 0;

                while (!fl.eof())
                {
                    char[] line = strip(fl.readLine());
                    if(line != "") /* don't count empty lines */
                        cntLn++;                    
                }
                fl.close();                 
                outputData ~= `"` ~ de.name ~ `","` ~ toString(cntLn) ~ `"` ~ \r\n;
            }
        }
        return true; // continue
    }

    std.file.listdir(pathname, & callback);
    return n;
}

Sample batch file

@echo off
dmd LinesOfCodeExample.d
LinesOfCodeExample.exe "\.(h|hpp|bak|d|vbs|c|cpp|exe)$" C:\w32api-3.1\include C:\examples\loc.csv
pause	

Source

Partially based on digitalmars.D/33287 (listdir example).