Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count files in directory with Dlang

Tags:

d

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..");
like image 397
Iain S Avatar asked Feb 04 '13 15:02

Iain S


2 Answers

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.

like image 142
Jonathan M Davis Avatar answered Nov 06 '22 17:11

Jonathan M Davis


You can use count from std.algorithm.

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

void main() {
    writeln(count(dirEntries(".", "*.txt", SpanMode.shallow)), " files found");
}
like image 39
Chris Cain Avatar answered Nov 06 '22 17:11

Chris Cain