Iain S
Iain S

Reputation: 2713

Count files in directory with Dlang

I would like an easy way to count the number of files in a directory using D.

As far as I can tell from the D manual, dirEntries returns a range, but this has no length property. I therefore have to iterate through the results with a counter, or gather up the names in a traditional array which I can find the length of... Is there a better way?

auto txtFiles = dirEntries(".", "*.txt", SpanMode.shallow);

int i=0;
foreach (txtFile; txtFiles)
    i++;

writeln(i, " files found..");

Upvotes: 6

Views: 785

Answers (2)

Jonathan M Davis
Jonathan M Davis

Reputation: 38287

Ranges generally don't have a length property unless it can be calculated in O(1). Any range which can't calculate its length in better than O(n) isn't going to have a length property, because it's too inefficient. The idiomatic way to get the length of a range with no length property is to use std.range.walkLength. It uses length if the range defines length; otherwise, it simply iterates over the range and counts up how many elements there are.

You can also use std.algorithm.count, but it's intended for counting the number of elements which match a predicate, and while it defaults to a predicate which returns true for every element, that's less efficient than walkLength, because walkLength doesn't call anything on the elements as it iterates over them, and it will use length instead if it's been defined, whereas count never will.

Upvotes: 15

Chris Cain
Chris Cain

Reputation: 666

You can use count from std.algorithm.

import std.algorithm, std.stdio, std.file;

void main() {
    writeln(count(dirEntries(".", "*.txt", SpanMode.shallow)), " files found");
}

Upvotes: 6

Related Questions