copying directories recursively
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jan 17 16:35:50 PST 2016
TL;DR: Is there a simple way to copy directories recursively?
My goal is to copy the directories ./src/dlang.org/{css,images,js} and
their contents to ./ddo/{css,images,js}.
Naively I tried this:
----
void main()
{
import file = std.file;
auto outputPath = "./ddo/";
foreach (dir; ["css", "images", "js"])
{
file.copy("./src/dlang.org/" ~ dir, outputPath ~ dir);
}
}
----
But that fails with "std.file.FileException at std/file.d(3154):
src/dlang.org/css: Is a directory".
`copy` doesn't have a parameter to enable copying directories, and I
can't find any `copyDir` or `copyRecurse` or some such.
As it looks I'll end up implementing my own `copyRecurse`:
----
void copyRecurse(string from, string to)
{
import std.file: copy, dirEntries, isDir, isFile, mkdirRecurse,
SpanMode;
import std.path: buildNormalizedPath, buildPath;
from = buildNormalizedPath(from);
to = buildNormalizedPath(to);
if (isDir(from))
{
mkdirRecurse(to);
auto entries = dirEntries(from, SpanMode.breadth);
foreach (entry; entries)
{
auto dst = buildPath(to, entry.name[from.length + 1 .. $]);
// + 1 for the directory separator
if (isFile(entry.name)) copy(entry.name, dst);
else mkdirRecurse(dst);
}
}
else copy(from, to);
}
----
Is there a simpler way to do this?
More information about the Digitalmars-d-learn
mailing list