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

listdir Example

Part of StandardLibraryCategory

Description

Uses std.file.listdir and std.regexp.RegExp to recursively list the files in a given path that match a particular regular expression.

Example

import std.file;
import std.stdio;
import std.string;

int main(char[][] args)
{
	char[] pattern;
	char[] ROOT;
	if(args.length > 1) /* first argument overrides ROOT */
		ROOT = args[1];
	else
		ROOT = r"c:\dm";
	if(args.length > 2) /* second argument overrides pattern */
		pattern = args[2];
	else
		pattern = r"\.(h|hpp|bak|d|vbs|c|cpp|exe)$";

    ulong n = 0;

    char[][] fs = listdir(ROOT, pattern);

    foreach(char[] fe; fs)
    {
		writefln("File: %s", fe);
        ++n;
    }

    writefln("Number: %s", n);

    return 0;
}

import std.regexp;

char[][] listdir(char[] pathname, char[] pattern)
{   char[][] result;
    auto r = new RegExp(pattern);

    bool callback(DirEntry* de)
    {
        if (de.isdir)
            std.file.listdir(de.name, & callback);
        else
        {   if (r.test(de.name))
                result ~= de.name;
        }
        return true; // continue
    }

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

Sample Batch File

echo off
dmd ListDirExample.d
ListDirExample.exe
ListDirExample.exe "c:\dmd" \.(lib)$
pause

Compatibility Notes

Tested with Digital Mars D Compiler v0.162 on Windows 2000.

Source

Based on digitalmars.D/33244 by Walter Bright.