Search code examples
d

dirEntries with walklength returns no files


I am working with dirEntries. Great function by the way. I wanted to test for the number of files before I used a foreach on it. I looked here on stack overflow and the suggested method was to use the walkLength function (Count files in directory with Dlang). I took that suggestion. The return from it was a non-zero value - great. However, the foreach will not iterate over the result of dirEntries. It acts like the walkLength has left the dirEntries at the end of the range. Is there a way to reset it so I can start at the beginning of the dirEntries list? Here is some example code:

auto dFiles = dirEntries("",filter, SpanMode.shallow);
if (walkLength(dFiles) > 0)
{
    writeln("Passed walkLength function");
    foreach (src; dFiles)
    {
        writeln("Inside foreach");
    }
}

The output shows it gets past the walkLength function, but never gets inside the foreach iterator.

Am I using dirEntries wrong? I have looked at Ali Cehreli's great book Programming in D as someone suggest. Nothing stuck out at me. I have looked online and nothing points to my interpretation of the problem. Of course, I could be completely off base on what the problem really is.


Solution

  • dirEntries gives you a range. You consume that range with walkLength and reach its end. Then you attempt to read more entries from it with the foreach loop. However, you have already reached its end, so there is nothing more to read.

    You can either repeat the dirEntries call, use the array function from std.array to convert the range to an array, or use the .save function to create a copy of the range that you pass to walkLength.

    If you don't care about the length and only care about whether it's empty, you can use the .empty property of the range instead of walkLength.