Read files in a directory using Dlang

I would like a simple 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 property has no length. So I have to iterate over the results using a counter or collect names in a traditional array that can find the length ... Is there a better way?

auto txtFiles = dirEntries(".", "*.txt", SpanMode.shallow); int i=0; foreach (txtFile; txtFiles) i++; writeln(i, " files found.."); 
+4
source share
2 answers

Ranges usually do not have the length property if it cannot be calculated in O(1) . Any range that cannot calculate its length better than O(n) will not have the length property, because it is too inefficient. The idiomatic way to get the length of a range without the 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 the number of elements.

You can also use std.algorithm.count , but it is designed to count the number of elements matching the predicate, and while the default is a predicate that returns true for each element, which is less efficient than walkLength , since walkLength does not call anything on elements, since iterates over them, and it will use length instead if it is defined, whereas count will never be.

+13
source

You can use count from std.algorithm .

 import std.algorithm, std.stdio, std.file; void main() { writeln(count(dirEntries(".", "*.txt", SpanMode.shallow)), " files found"); } 
+4
source

All Articles