Directory recursive walking

drug drug2004 at bk.ru
Thu Jan 14 16:18:28 UTC 2021


On 1/14/21 7:06 PM, dog2002 wrote:
> On Thursday, 14 January 2021 at 16:01:43 UTC, drug wrote:
>> On 1/14/21 6:55 PM, drug wrote:
>>>>
>>>> But this method consumes a huge amount of memory (up to 4 GB and 
>>>> more). Is there a more appropriate way to walk directories 
>>>> recursively that does not consume a lot of memory?
>>>
>>> DirEntry is a struct. First of all I would try this:
>>> ```D
>>> foreach(ref entry; dirEntries(path, SpanMode.shallow, false))
>>> ```
>>
>> Does your directory just contain large amount of files?
> 
> Yes. I forgot to add it in the original post.

Does using `ref` changed anything?
Try following:
```
import std;

void DirIteration(ref DirEntry dir) {
     try {
         foreach(ref entry; dirEntries(dir, SpanMode.shallow, false)) { 
//SpanMode.shallow allows skip directories if any error happens
             if (entry.isFile && !entry.isSymlink)
                 writeln(entry); //Or something instead of this
             if (entry.isDir)
                 DirIteration(entry);
         }
     }
     catch (Throwable) {}
}

void main()
{
     auto de = DirEntry(".");
     DirIteration(de);
}
```


More information about the Digitalmars-d-learn mailing list