Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through files in a folder in D

Tags:

d

In D programming, how can I iterate through all files in a folder? Is there a D counterpart to python's glob.iglob?


2 Answers

http://dlang.org/phobos/std_file.html#dirEntries

So like

import std.file;
foreach(string filename; dirEntries("folder_name", "*.txt", SpanMode.shallow) {
     // do something with filename
}

See the docs for more info. The second string, the *.txt filter, is optional, if you leave it out, you see all files.

The SpanMode can be shallow to skip going into subfolders or something like SpanMode.depth to descend into them.

like image 114
Adam D. Ruppe Avatar answered Dec 07 '25 15:12

Adam D. Ruppe


Take a look at std.file.dirEntries. It will allow you to iterate over all of the files in a directory either shallowly (so it doesn't iterate any subdirectories), with breadth-first search, or with depth-first search. And you can tell it whether you want it to follow symlinks or not. It also supports wildcard strings using std.path.globMatch. A basic example would be something like

foreach(DirEntry de; dirEntries(myDirectory, SpanMode.shallow))
{
    ...
}

However, because dirEntries returns a range of DirEntrys, it can be used in the various range-based functions in Phobos and not just with foreach.

like image 42
Jonathan M Davis Avatar answered Dec 07 '25 15:12

Jonathan M Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!