问题
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..");
回答1:
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.
回答2:
You can use count from std.algorithm.
import std.algorithm, std.stdio, std.file;
void main() {
writeln(count(dirEntries(".", "*.txt", SpanMode.shallow)), " files found");
}
来源:https://stackoverflow.com/questions/14689708/count-files-in-directory-with-dlang