Function std.file.dirEntries
Returns an input range
of DirEntry
that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string
if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
std .file .DirIterator dirEntries
(
string path,
SpanMode mode,
bool followSymlink = true
);
std .algorithm .iteration .FilterResult!(std.file.dirEntries(string,string,std.file.SpanMode,bool).f(std.file.DirEntry),std.file.DirIterator) dirEntries
(
string path,
string pattern,
SpanMode mode,
bool followSymlink = true
);
Note
The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.
Parameters
Returns
An input range of
DirEntry
.
Throws
FileException
if the directory does not exist.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode .depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode .breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode .breadth))
{
writeln(e .name, "\t", e .size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode .depth) .filter!(f => f .name .endsWith(".d"));
foreach (d; dFiles)
writeln(d .name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d .name;
writeln(cmd);
executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode .depth);
foreach (d; dFiles)
writeln(d .name);
Example
Duplicate functionality of D1's std
:
string[] listdir(string pathname)
{
import std .algorithm;
import std .array;
import std .file;
import std .path;
return std .file .dirEntries(pathname, SpanMode .shallow)
.filter!(a => a .isFile)
.map!((return a) => baseName(a .name))
.array;
}
void main(string[] args)
{
import std .stdio;
string[] files = listdir(args[1]);
writefln("%s", files);
}