Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.file

Utilities for manipulating files and scanning directories. Functionsin this module handle files as a unit, e.g., read or write one fileat a time. For opening files and manipulating them via handles referto modulestd.stdio.
CategoryFunctions
GeneralexistsisDirisFileisSymlinkrenamethisExePath
DirectorieschdirdirEntriesgetcwdmkdirmkdirRecursermdirrmdirRecursetempDir
FilesappendcopyreadreadTextremoveslurpwrite
SymlinkssymlinkreadLink
AttributesattrIsDirattrIsFileattrIsSymlinkgetAttributesgetLinkAttributesgetSizesetAttributes
TimestampgetTimesgetTimesWinsetTimestimeLastModifiedtimeLastAccessedtimeStatusChanged
OtherDirEntryFileExceptionPreserveAttributesSpanModegetAvailableDiskSpace
See Also:
Theofficial tutorial for anintroduction to working with files in D, modulestd.stdio for opening files and manipulating them via handles,and modulestd.path for manipulating path strings.
License:
Boost License 1.0.
Authors:
Walter Bright,Andrei Alexandrescu,Jonathan M Davis

Sourcestd/file.d

classFileException:object.Exception;
Exception thrown for file I/O errors.
Examples:
import std.exception : assertThrown;assertThrown!FileException("non.existing.file.".readText);
immutable uinterrno;
OS error code.
pure @safe this(scope const(char)[]name, scope const(char)[]msg, stringfile = __FILE__, size_tline = __LINE__);
Constructor which takes an error message.
Parameters:
const(char)[]nameName of file for which the error occurred.
const(char)[]msgMessage describing the error.
stringfileThe file where the error occurred.
size_tlineThe line where the error occurred.
@trusted this(scope const(char)[]name, uinterrno = .errno, stringfile = __FILE__, size_tline = __LINE__);
Constructor which takes the error number (GetLastError in Windows,errno in POSIX).
Parameters:
const(char)[]nameName of file for which the error occurred.
uinterrnoThe error number.
stringfileThe file where the error occurred. Defaults to__FILE__.
size_tlineThe line where the error occurred. Defaults to__LINE__.
void[]read(R)(Rname, size_tupTo = size_t.max)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

void[]read(R)(auto ref Rname, size_tupTo = size_t.max)
if (isConvertibleToString!R);
Read entire contents of filename and returns it as an untypedarray. If the file size is larger thanupTo, onlyupTobytes are read.
Parameters:
Rnamestring or range of characters representing the file name
size_tupToif present, the maximum number of bytes to read
Returns:
Untyped array of bytes read.
Throws:
FileException on error.
See Also:
std.file.readText for reading and validating a text file.
Examples:
import std.utf : byChar;scope(exit){assert(exists(deleteme));    remove(deleteme);}std.file.write(deleteme,"1234");// deleteme is the name of a temporary filewriteln(read(deleteme, 2));// "12"writeln(read(deleteme.byChar));// "1234"writeln((cast(const(ubyte)[])read(deleteme)).length);// 4
SreadText(S = string, R)(auto ref Rname)
if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)));
Reads and validates (usingstd.utf.validate) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.
Parameters:
Sthe string type of the file
Rnamestring or range of characters representing the file name
Returns:
Array of characters read.
Throws:
FileException if there is an error reading the file,std.utf.UTFException on UTF decoding error.
See Also:
std.file.read for reading a binary file.
Examples:
Read file with UTF-8 text.
write(deleteme,"abc");// deleteme is the name of a temporary filescope(exit) remove(deleteme);string content =readText(deleteme);writeln(content);// "abc"
voidwrite(R)(Rname, const void[]buffer)
if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R);

voidwrite(R)(auto ref Rname, const void[]buffer)
if (isConvertibleToString!R);
Writebuffer to filename.
Creates the file if it does not already exist.
Parameters:
Rnamestring or range of characters representing the file name
void[]bufferdata to be written to file
Throws:
FileException on error.
See Also:
Examples:
scope(exit){assert(exists(deleteme));    remove(deleteme);}int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];write(deleteme, a);// deleteme is the name of a temporary fileconst bytes = read(deleteme);const fileInts = () @trusted {returncast(int[]) bytes; }();writeln(fileInts);// a
voidappend(R)(Rname, const void[]buffer)
if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R);

voidappend(R)(auto ref Rname, const void[]buffer)
if (isConvertibleToString!R);
Appendsbuffer to filename.
Creates the file if it does not already exist.
Parameters:
Rnamestring or range of characters representing the file name
void[]bufferdata to be appended to file
Throws:
FileException on error.
Examples:
scope(exit){assert(exists(deleteme));    remove(deleteme);}int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];write(deleteme, a);// deleteme is the name of a temporary fileint[] b = [ 13, 21 ];append(deleteme, b);const bytes = read(deleteme);const fileInts = () @trusted {returncast(int[]) bytes; }();writeln(fileInts);// a ~ b
voidrename(RF, RT)(RFfrom, RTto)
if ((isSomeFiniteCharInputRange!RF || isSomeString!RF) && !isConvertibleToString!RF && (isSomeFiniteCharInputRange!RT || isSomeString!RT) && !isConvertibleToString!RT);

voidrename(RF, RT)(auto ref RFfrom, auto ref RTto)
if (isConvertibleToString!RF || isConvertibleToString!RT);
Rename filefrom toto, moving it between directories if required. If the target file exists, it is overwritten.
It is not possible to rename a file across different mount points or drives. On POSIX, the operation is atomic. That means, ifto already exists there will be no time period during the operation whereto is missing. Seemanpage for rename for more details.
Parameters:
RFfromstring or range of characters representing the existing file name
RTtostring or range of characters representing the target file name
Throws:
FileException on error.
Examples:
auto t1 = deleteme, t2 = deleteme~"2";scope(exit)foreach (t; [t1, t2])if (t.exists) t.remove();t1.write("1");t1.rename(t2);writeln(t2.readText);// "1"t1.write("2");t1.rename(t2);writeln(t2.readText);// "2"
voidremove(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidremove(R)(auto ref Rname)
if (isConvertibleToString!R);
Delete filename.
Parameters:
Rnamestring or range of characters representing the file name
Throws:
FileException on error.
Examples:
import std.exception : assertThrown;deleteme.write("Hello");writeln(deleteme.readText);// "Hello"deleteme.remove;assertThrown!FileException(deleteme.readText);
ulonggetSize(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

ulonggetSize(R)(auto ref Rname)
if (isConvertibleToString!R);
Get size of filename in bytes.
Parameters:
Rnamestring or range of characters representing the file name
Returns:
The size of file in bytes.
Throws:
FileException on error (e.g., file not found).
Examples:
scope(exit) deleteme.remove;// create a file of size 1write(deleteme,"a");writeln(getSize(deleteme));// 1// create a file of size 3write(deleteme,"abc");writeln(getSize(deleteme));// 3
voidgetTimes(R)(Rname, out SysTimeaccessTime, out SysTimemodificationTime)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidgetTimes(R)(auto ref Rname, out SysTimeaccessTime, out SysTimemodificationTime)
if (isConvertibleToString!R);
Get the access and modified times of file or foldername.
Parameters:
RnameFile/Folder name to get times for.
SysTimeaccessTimeTime the file/folder was last accessed.
SysTimemodificationTimeTime the file/folder was last modified.
Throws:
FileException on error.
Examples:
import std.datetime : abs, SysTime;scope(exit) deleteme.remove;write(deleteme,"a");SysTimeaccessTime,modificationTime;getTimes(deleteme,accessTime,modificationTime);import std.datetime : Clock, seconds;auto currTime = Clock.currTime();enum leeway = 5.seconds;auto diffAccess =accessTime - currTime;auto diffModification =modificationTime - currTime;assert(abs(diffAccess) <= leeway);assert(abs(diffModification) <= leeway);
voidgetTimesWin(R)(Rname, out SysTimefileCreationTime, out SysTimefileAccessTime, out SysTimefileModificationTime)
if (isSomeFiniteCharInputRange!R || isConvertibleToString!R);
This function is Windows-Only.
Get creation/access/modified times of filename.
This is the same asgetTimes except that it also gives you the file creation time - which isn't possible on POSIX systems.
Parameters:
RnameFile name to get times for.
SysTimefileCreationTimeTime the file was created.
SysTimefileAccessTimeTime the file was last accessed.
SysTimefileModificationTimeTime the file was last modified.
Throws:
FileException on error.
voidsetTimes(R)(Rname, SysTimeaccessTime, SysTimemodificationTime)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidsetTimes(R)(auto ref Rname, SysTimeaccessTime, SysTimemodificationTime)
if (isConvertibleToString!R);
Set access/modified times of file or foldername.
Parameters:
RnameFile/Folder name to get times for.
SysTimeaccessTimeTime the file/folder was last accessed.
SysTimemodificationTimeTime the file/folder was last modified.
Throws:
FileException on error.
Examples:
import std.datetime : DateTime, hnsecs, SysTime;scope(exit) deleteme.remove;write(deleteme,"a");SysTimeaccessTime = SysTime(DateTime(2010, 10, 4, 0, 0, 30));SysTimemodificationTime = SysTime(DateTime(2018, 10, 4, 0, 0, 30));setTimes(deleteme,accessTime,modificationTime);SysTime accessTimeResolved, modificationTimeResolved;getTimes(deleteme, accessTimeResolved, modificationTimeResolved);writeln(accessTime);// accessTimeResolvedwriteln(modificationTime);// modificationTimeResolved
SysTimetimeLastModified(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

SysTimetimeLastModified(R)(auto ref Rname)
if (isConvertibleToString!R);
Returns the time that the given file was last modified.
Parameters:
Rnamethe name of the file to check
Returns:
Throws:
FileException if the given file does not exist.
Examples:
import std.datetime : abs, DateTime, hnsecs, SysTime;scope(exit) deleteme.remove;import std.datetime : Clock, seconds;auto currTime = Clock.currTime();enum leeway = 5.seconds;deleteme.write("bb");assert(abs(deleteme.timeLastModified - currTime) <= leeway);
SysTimetimeLastModified(R)(Rname, SysTimereturnIfMissing)
if (isSomeFiniteCharInputRange!R);
Returns the time that the given file was last modified. If the file does not exist, returnsreturnIfMissing.
A frequent usage pattern occurs in build automation tools such asmake orant. To check whether file target must be rebuilt from filesource (i.e.,target is older thansource or does not exist), use the comparison below. The code throws aFileException ifsource does not exist (as it should). On the other hand, theSysTime.min default makes a non-existingtarget seem infinitely old so the test correctly prompts building it.
Parameters:
RnameThe name of the file to get the modification time for.
SysTimereturnIfMissingThe time to return if the given file does not exist.
Returns:

Example

if (source.timeLastModified >= target.timeLastModified(SysTime.min)){// must (re)build}else{// target is up-to-date}

Examples:
import std.datetime : SysTime;writeln("file.does.not.exist".timeLastModified(SysTime.min));// SysTime.minauto source = deleteme ~"source";auto target = deleteme ~"target";scope(exit) source.remove, target.remove;source.write(".");assert(target.timeLastModified(SysTime.min) < source.timeLastModified);target.write(".");assert(target.timeLastModified(SysTime.min) >= source.timeLastModified);
pure nothrow SysTimetimeLastModified()(auto ref stat_tstatbuf);
This function is POSIX-Only.
Returns the time that the given file was last modified.
Parameters:
stat_tstatbufstat_t retrieved from file.
pure nothrow SysTimetimeLastAccessed()(auto ref stat_tstatbuf);
This function is POSIX-Only.
Returns the time that the given file was last accessed.
Parameters:
stat_tstatbufstat_t retrieved from file.
pure nothrow SysTimetimeStatusChanged()(auto ref stat_tstatbuf);
This function is POSIX-Only.
Returns the time that the given file was last changed.
Parameters:
stat_tstatbufstat_t retrieved from file.
boolexists(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

boolexists(R)(auto ref Rname)
if (isConvertibleToString!R);
Determine whether the given file (or directory) exists.
Parameters:
Rnamestring or range of characters representing the file name
Returns:
true if the file name specified as input exists
Examples:
auto f = deleteme ~"does.not.exist";assert(!f.exists);f.write("hello");assert(f.exists);f.remove;assert(!f.exists);
uintgetAttributes(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

uintgetAttributes(R)(auto ref Rname)
if (isConvertibleToString!R);
Returns the attributes of the given file.
Note that the file attributes on Windows and POSIX systems are completely different. On Windows, they're what is returned by GetFileAttributes, whereas on POSIX systems, they're thest_mode value which is part of thestat struct gotten by calling thestat function.
On POSIX systems, if the given file is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.
Parameters:
RnameThe file to get the attributes of.
Returns:
The attributes of the file as auint.
Throws:
FileException on error.
Examples:
getAttributes with a file
import std.exception : assertThrown;auto f = deleteme ~"file";scope(exit) f.remove;assert(!f.exists);assertThrown!FileException(f.getAttributes);f.write(".");auto attributes = f.getAttributes;assert(!attributes.attrIsDir);assert(attributes.attrIsFile);
Examples:
getAttributes with a directory
import std.exception : assertThrown;auto dir = deleteme ~"dir";scope(exit) dir.rmdir;assert(!dir.exists);assertThrown!FileException(dir.getAttributes);dir.mkdir;auto attributes = dir.getAttributes;assert(attributes.attrIsDir);assert(!attributes.attrIsFile);
uintgetLinkAttributes(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

uintgetLinkAttributes(R)(auto ref Rname)
if (isConvertibleToString!R);
If the given file is a symbolic link, then this returns the attributes of the symbolic link itself rather than file that it points to. If the given file isnot a symbolic link, then this function returns the same result as getAttributes.
On Windows, getLinkAttributes is identical to getAttributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links.
Parameters:
RnameThe file to get the symbolic link attributes of.
Returns:
the attributes
Throws:
FileException on error.
Examples:
import std.exception : assertThrown;auto source = deleteme ~"source";auto target = deleteme ~"target";assert(!source.exists);assertThrown!FileException(source.getLinkAttributes);// symlinking isn't available on Windowsversion (Posix){scope(exit) source.remove, target.remove;    target.write("target");    target.symlink(source);    writeln(source.readText);// "target"assert(source.isSymlink);assert(source.getLinkAttributes.attrIsSymlink);}
Examples:
if the file is no symlink, getLinkAttributes behaves like getAttributes
import std.exception : assertThrown;auto f = deleteme ~"file";scope(exit) f.remove;assert(!f.exists);assertThrown!FileException(f.getLinkAttributes);f.write(".");auto attributes = f.getLinkAttributes;assert(!attributes.attrIsDir);assert(attributes.attrIsFile);
Examples:
if the file is no symlink, getLinkAttributes behaves like getAttributes
import std.exception : assertThrown;auto dir = deleteme ~"dir";scope(exit) dir.rmdir;assert(!dir.exists);assertThrown!FileException(dir.getLinkAttributes);dir.mkdir;auto attributes = dir.getLinkAttributes;assert(attributes.attrIsDir);assert(!attributes.attrIsFile);
voidsetAttributes(R)(Rname, uintattributes)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidsetAttributes(R)(auto ref Rname, uintattributes)
if (isConvertibleToString!R);
Set the attributes of the given file.
For example, a programmatic equivalent of Unix'schmod +xname to make a file executable isname.setAttributes(name.getAttributes | octal!700).
Parameters:
Rnamethe file name
uintattributesthe attributes to set the file to
Throws:
FileException if the given file does not exist.
Examples:
setAttributes with a file
import std.exception : assertThrown;import std.conv : octal;auto f = deleteme ~"file";version (Posix){scope(exit) f.remove;assert(!f.exists);    assertThrown!FileException(f.setAttributes(octal!777));    f.write(".");autoattributes = f.getAttributes;assert(!attributes.attrIsDir);assert(attributes.attrIsFile);    f.setAttributes(octal!777);attributes = f.getAttributes;    writeln((attributes & 1023));// octal!777}
Examples:
setAttributes with a directory
import std.exception : assertThrown;import std.conv : octal;auto dir = deleteme ~"dir";version (Posix){scope(exit) dir.rmdir;assert(!dir.exists);    assertThrown!FileException(dir.setAttributes(octal!777));    dir.mkdir;autoattributes = dir.getAttributes;assert(attributes.attrIsDir);assert(!attributes.attrIsFile);    dir.setAttributes(octal!777);attributes = dir.getAttributes;    writeln((attributes & 1023));// octal!777}
@property boolisDir(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

@property boolisDir(R)(auto ref Rname)
if (isConvertibleToString!R);
Returns whether the given file is a directory.
Parameters:
RnameThe path to the file.
Returns:
true if name specifies a directory
Throws:
FileException if the given file does not exist.
Examples:
import std.exception : assertThrown;auto dir = deleteme ~"dir";auto f = deleteme ~"f";scope(exit) dir.rmdir, f.remove;assert(!dir.exists);assertThrown!FileException(dir.isDir);dir.mkdir;assert(dir.isDir);f.write(".");assert(!f.isDir);
pure nothrow @nogc @safe boolattrIsDir(uintattributes);
Returns whether the given file attributes are for a directory.
Parameters:
uintattributesThe file attributes.
Returns:
true if attributes specifies a directory
Examples:
import std.exception : assertThrown;auto dir = deleteme ~"dir";auto f = deleteme ~"f";scope(exit) dir.rmdir, f.remove;assert(!dir.exists);assertThrown!FileException(dir.getAttributes.attrIsDir);dir.mkdir;assert(dir.isDir);assert(dir.getAttributes.attrIsDir);f.write(".");assert(!f.isDir);assert(!f.getAttributes.attrIsDir);
@property boolisFile(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

@property boolisFile(R)(auto ref Rname)
if (isConvertibleToString!R);
Returns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So, eitherisFile orisDir will return true for any given file.
On POSIX systems, ifisFile istrue, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for bothisFile andisDir to befalse for a particular file (in which case, it's a special file). You can usegetAttributes to get the attributes to figure out what type of special it is, or you can useDirEntry to get at itsstatBuf, which is the result fromstat. In either case, see the man page forstat for more information.
Parameters:
RnameThe path to the file.
Returns:
true if name specifies a file
Throws:
FileException if the given file does not exist.
Examples:
import std.exception : assertThrown;auto dir = deleteme ~"dir";auto f = deleteme ~"f";scope(exit) dir.rmdir, f.remove;dir.mkdir;assert(!dir.isFile);assert(!f.exists);assertThrown!FileException(f.isFile);f.write(".");assert(f.isFile);
pure nothrow @nogc @safe boolattrIsFile(uintattributes);
Returns whether the given file attributes are for a file.
On Windows, if a file is not a directory, it's a file. So, eitherattrIsFile orattrIsDir will returntrue for the attributes of any given file.
On POSIX systems, ifattrIsFile istrue, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for bothattrIsFile andattrIsDir to befalse for a particular file (in which case, it's a special file). If a file is a special file, you can use the attributes to check what type of special file it is (see the man page forstat for more information).
Parameters:
uintattributesThe file attributes.
Returns:
true if the given file attributes are for a file

Example

assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf")));assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));

Examples:
import std.exception : assertThrown;auto dir = deleteme ~"dir";auto f = deleteme ~"f";scope(exit) dir.rmdir, f.remove;dir.mkdir;assert(!dir.isFile);assert(!dir.getAttributes.attrIsFile);assert(!f.exists);assertThrown!FileException(f.getAttributes.attrIsFile);f.write(".");assert(f.isFile);assert(f.getAttributes.attrIsFile);
@property boolisSymlink(R)(Rname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

@property boolisSymlink(R)(auto ref Rname)
if (isConvertibleToString!R);
Returns whether the given file is a symbolic link.
On Windows, returnstrue when the file is either a symbolic link or a junction point.
Parameters:
RnameThe path to the file.
Returns:
true if name is a symbolic link
Throws:
FileException if the given file does not exist.
Examples:
import std.exception : assertThrown;auto source = deleteme ~"source";auto target = deleteme ~"target";assert(!source.exists);assertThrown!FileException(source.isSymlink);// symlinking isn't available on Windowsversion (Posix){scope(exit) source.remove, target.remove;    target.write("target");    target.symlink(source);    writeln(source.readText);// "target"assert(source.isSymlink);assert(source.getLinkAttributes.attrIsSymlink);}
pure nothrow @nogc @safe boolattrIsSymlink(uintattributes);
Returns whether the given file attributes are for a symbolic link.
On Windows, returntrue when the file is either a symbolic link or a junction point.
Parameters:
uintattributesThe file attributes.
Returns:
true if attributes are for a symbolic link

Example

core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf","/tmp/alink");assert(!getAttributes("/tmp/alink").isSymlink);assert(getLinkAttributes("/tmp/alink").isSymlink);

Examples:
import std.exception : assertThrown;auto source = deleteme ~"source";auto target = deleteme ~"target";assert(!source.exists);assertThrown!FileException(source.getLinkAttributes.attrIsSymlink);// symlinking isn't available on Windowsversion (Posix){scope(exit) source.remove, target.remove;    target.write("target");    target.symlink(source);    writeln(source.readText);// "target"assert(source.isSymlink);assert(source.getLinkAttributes.attrIsSymlink);}
voidchdir(R)(Rpathname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidchdir(R)(auto ref Rpathname)
if (isConvertibleToString!R);
Change directory topathname. Equivalent tocd onWindows and POSIX.
Parameters:
Rpathnamethe directory to step into
Throws:
FileException on error.
Examples:
import std.algorithm.comparison : equal;import std.algorithm.sorting : sort;import std.array : array;import std.path : buildPath;auto cwd = getcwd;auto dir = deleteme ~"dir";dir.mkdir;scope(exit) cwd.chdir, dir.rmdirRecurse;dir.buildPath("a").write(".");dir.chdir;// step into dir"b".write(".");assert(dirEntries(".", SpanMode.shallow).array.sort.equal(    [".".buildPath("a"),".".buildPath("b")]));
voidmkdir(R)(Rpathname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidmkdir(R)(auto ref Rpathname)
if (isConvertibleToString!R);
Make a new directorypathname.
Parameters:
Rpathnamethe path of the directory to make
Throws:
FileException on POSIX orWindowsException on Windows if an error occured.
Examples:
import std.file :mkdir;auto dir = deleteme ~"dir";scope(exit) dir.rmdir;dir.mkdir;assert(dir.exists);
Examples:
import std.exception : assertThrown;assertThrown("a/b/c/d/e".mkdir);
@safe voidmkdirRecurse(scope const(char)[]pathname);
Make directory and all parent directories as needed.
Does nothing if the directory specified bypathname already exists.
Parameters:
const(char)[]pathnamethe full path of the directory to create
Throws:
FileException on error.
Examples:
import std.path : buildPath;auto dir = deleteme ~"dir";scope(exit) dir.rmdirRecurse;dir.mkdir;assert(dir.exists);dir.mkdirRecurse;// does nothing// creates all parent directories as neededauto nested = dir.buildPath("a","b","c");nested.mkdirRecurse;assert(nested.exists);
Examples:
import std.exception : assertThrown;scope(exit) deleteme.remove;deleteme.write("a");// cannot make directory as it's already a fileassertThrown!FileException(deleteme.mkdirRecurse);
voidrmdir(R)(Rpathname)
if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R);

voidrmdir(R)(auto ref Rpathname)
if (isConvertibleToString!R);
Remove directorypathname.
Parameters:
RpathnameRange or string specifying the directory name
Throws:
FileException on error.
Examples:
auto dir = deleteme ~"dir";dir.mkdir;assert(dir.exists);dir.rmdir;assert(!dir.exists);
voidsymlink(RO, RL)(ROoriginal, RLlink)
if ((isSomeFiniteCharInputRange!RO || isConvertibleToString!RO) && (isSomeFiniteCharInputRange!RL || isConvertibleToString!RL));
This function is POSIX-Only.
Creates a symbolic link (symlink).
Parameters:
ROoriginalThe file that is being linked. This is the target path that's stored in the symlink. A relative path is relative to the created symlink.
RLlinkThe symlink to create. A relative path is relative to the current working directory.
Throws:
FileException on error (which includes if the symlink already exists).
stringreadLink(R)(Rlink)
if (isSomeFiniteCharInputRange!R || isConvertibleToString!R);
This function is POSIX-Only.
Returns the path to the file pointed to by a symlink. Note that the path could be either relative or absolute depending on the symlink. If the path is relative, it's relative to the symlink, not the current working directory.
Throws:
FileException on error.
@trusted stringgetcwd();
Get the current working directory.
Throws:
FileException on error.
Examples:
auto s =getcwd();assert(s.length);
@trusted stringthisExePath();
Returns the full path of the current executable.
Returns:
The path of the executable as astring.
Throws:
Examples:
import std.path : isAbsolute;auto path =thisExePath();assert(path.exists);assert(path.isAbsolute);assert(path.isFile);
structDirEntry;
Info on a file, similar to what you'd get from stat on a POSIX system.
@safe this(return scope stringpath);
Constructs aDirEntry for the given file (or directory).
Parameters:
stringpathThe file (or directory) to get a DirEntry for.
Throws:
FileException if the file does not exist.
@property @safe stringname() const return scope;
Returns the path to the file represented by thisDirEntry.

Example

auto de1 = DirEntry("/etc/fonts/fonts.conf");assert(de1.name =="/etc/fonts/fonts.conf");auto de2 = DirEntry("/usr/share/include");assert(de2.name =="/usr/share/include");

@property @safe boolisDir();
Returns whether the file represented by thisDirEntry is a directory.

Example

auto de1 = DirEntry("/etc/fonts/fonts.conf");assert(!de1.isDir);auto de2 = DirEntry("/usr/share/include");assert(de2.isDir);

@property @safe boolisFile();
Returns whether the file represented by thisDirEntry is a file.
On Windows, if a file is not a directory, then it's a file. So, eitherisFile orisDir will returntrue.
On POSIX systems, ifisFile istrue, that indicates that the file is a regular file (e.g. not a block not device). So, on POSIX systems, it's possible for bothisFile andisDir to befalse for a particular file (in which case, it's a special file). You can useattributes orstatBuf to get more information about a special file (see the stat man page for more details).

Example

auto de1 = DirEntry("/etc/fonts/fonts.conf");assert(de1.isFile);auto de2 = DirEntry("/usr/share/include");assert(!de2.isFile);

@property @safe boolisSymlink();
Returns whether the file represented by thisDirEntry is a symbolic link.
On Windows, returntrue when the file is either a symbolic link or a junction point.
@property @safe ulongsize();
Returns the size of the file represented by thisDirEntry in bytes.
@property @safe SysTimetimeCreated() const;
This function is Windows-Only.
Returns the creation time of the file represented by thisDirEntry.
@property @safe SysTimetimeLastAccessed();
Returns the time that the file represented by thisDirEntry was last accessed.
Note that many file systems do not update the access time for files (generally for performance reasons), so there's a good chance thattimeLastAccessed will return the same value astimeLastModified.
@property @safe SysTimetimeLastModified();
Returns the time that the file represented by thisDirEntry was last modified.
@property @safe SysTimetimeStatusChanged() const;
This function is POSIX-Only.
Returns the time that the file represented by thisDirEntry was last changed (not only in contents, but also in permissions or ownership).
@property @safe uintattributes();
Returns the attributes of the file represented by thisDirEntry.
Note that the file attributes on Windows and POSIX systems are completely different. On, Windows, they're what is returned byGetFileAttributesGetFileAttributes Whereas, an POSIX systems, they're thest_mode value which is part of thestat struct gotten by callingstat.
On POSIX systems, if the file represented by thisDirEntry is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.
@property @safe uintlinkAttributes();
On POSIX systems, if the file represented by thisDirEntry is a symbolic link, thenlinkAttributes are the attributes of the symbolic link itself. Otherwise,linkAttributes is identical toattributes.
On Windows,linkAttributes is identical toattributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links.
@property @safe stat_tstatBuf();
This function is POSIX-Only.
Thestat struct gotten from callingstat.
PreserveAttributespreserveAttributesDefault;
Defaults toYes.preserveAttributes on Windows, and the opposite on all other platforms.
voidcopy(RF, RT)(RFfrom, RTto, PreserveAttributespreserve = preserveAttributesDefault)
if (isSomeFiniteCharInputRange!RF && !isConvertibleToString!RF && isSomeFiniteCharInputRange!RT && !isConvertibleToString!RT);

voidcopy(RF, RT)(auto ref RFfrom, auto ref RTto, PreserveAttributespreserve = preserveAttributesDefault)
if (isConvertibleToString!RF || isConvertibleToString!RT);
Copy filefrom to fileto. File timestamps are preserved.File attributes are preserved, ifpreserve equalsYes.preserveAttributes.On Windows onlyYes.preserveAttributes (the default on Windows) is supported.If the target file exists, it is overwritten.
Parameters:
RFfromstring or range of characters representing the existing file name
RTtostring or range of characters representing the target file name
PreserveAttributespreservewhether to preserve the file attributes
Throws:
FileException on error.
Examples:
auto source = deleteme ~"source";auto target = deleteme ~"target";auto targetNonExistent = deleteme ~"target2";scope(exit) source.remove, target.remove, targetNonExistent.remove;source.write("source");target.write("target");writeln(target.readText);// "target"source.copy(target);writeln(target.readText);// "source"source.copy(targetNonExistent);writeln(targetNonExistent.readText);// "source"
@safe voidrmdirRecurse(scope const(char)[]pathname);

@safe voidrmdirRecurse(ref scope DirEntryde);

@safe voidrmdirRecurse(scope DirEntryde);
Remove directory and all of its content and subdirectories, recursively.
Parameters:
const(char)[]pathnamethe path of the directory to completely remove
DirEntrydeTheDirEntry to remove
Throws:
FileException if there is an error (including if the given file is not a directory).
Examples:
import std.path : buildPath;auto dir = deleteme.buildPath("a","b","c");dir.mkdirRecurse;assert(dir.exists);deleteme.rmdirRecurse;assert(!dir.exists);assert(!deleteme.exists);
enumSpanMode: int;
Dictates directory spanning policy fordirEntries (see below).
Examples:
import std.algorithm.comparison : equal;import std.algorithm.iteration : map;import std.algorithm.sorting : sort;import std.array : array;import std.path : buildPath, relativePath;auto root = deleteme ~"root";scope(exit) root.rmdirRecurse;root.mkdir;root.buildPath("animals").mkdir;root.buildPath("animals","cat").mkdir;alias removeRoot = (returnscope e) => e.relativePath(root);assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(    [buildPath("animals","cat"),"animals"]));assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(    ["animals", buildPath("animals","cat")]));root.buildPath("plants").mkdir;assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(    ["animals","plants"]));
shallow
Only spans one directory.
depth
Spans the directory in depth-firstpost-order, i.e. the content of any subdirectory is spanned before that subdirectory itself. Useful e.g. when recursively deleting files.
breadth
Spans the directory indepth-firstpre-order, i.e. the content of any subdirectory is spanned right after that subdirectory itself.
Note thatSpanMode.breadth will not result in all directory members occurring before any subdirectory members, i.e. it is not true breadth-first traversal.
autodirEntries(bool useDIP1000 = dip1000Enabled)(stringpath, SpanModemode, boolfollowSymlink = true);

autodirEntries(bool useDIP1000 = dip1000Enabled)(stringpath, stringpattern, SpanModemode, boolfollowSymlink = true);
Returns aninput range ofDirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of typestring if only the name is needed, orDirEntry 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).

NoteThe order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Parameters:
useDIP1000used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.
stringpathThe directory to iterate over. If empty, the current directory will be iterated.
stringpatternOptional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under std.path.globMatch.
SpanModemodeWhether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).
boolfollowSymlinkWhether symbolic links which point to directories should be treated as directories and their contents iterated over.
Returns:
Throws:
  • FileException if thepath directory does not exist or read permission is denied.
  • FileException ifmode is notshallow and a subdirectory cannot be read.

Example

// Iterate a directory in depthforeach (string name;dirEntries("destroy/me", SpanMode.depth)){    remove(name);}// Iterate the current directory in breadthforeach (string name;dirEntries("", SpanMode.breadth)){    writeln(name);}// Iterate a directory and get detailed info about itforeach (DirEntry e;dirEntries("dmd-testing", SpanMode.breadth)){    writeln(e.name,"\t", e.size);}// Iterate over all *.d files in current directory and all its subdirectoriesauto 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);    std.process.executeShell(cmd);}// Iterate over all D source files in current directory and all its// subdirectoriesauto dFiles =dirEntries("","*.{d,di}",SpanMode.depth);foreach (d; dFiles)    writeln(d.name);
To handle subdirectories with denied read permission, useSpanMode.shallow:
void scan(stringpath){foreach (DirEntry entry;dirEntries(path, SpanMode.shallow))    {try        {            writeln(entry.name);if (entry.isDir)                scan(entry.name);        }catch (FileException fe) {continue; }// ignore    }}scan("");

Examples:
Duplicate functionality of D1'sstd.file.listdir():
string[] listdir(string pathname){import std.algorithm.iteration : map, filter;import std.array : array;import std.path : baseName;returndirEntries(pathname, SpanMode.shallow)        .filter!(a => a.isFile)        .map!((return a) => baseName(a.name))        .array;}// Can be safe only with -preview=dip1000@safevoid main(string[] args){import std.stdio : writefln;    string[] files = listdir(args[1]);    writefln("%s", files);}
Select!(Types.length == 1, Types[0][], Tuple!Types[])slurp(Types...)(stringfilename, scope const(char)[]format);
Reads a file line by line and parses the line into a single value or astd.typecons.Tuple of values depending on the length ofTypes. The lines are parsed using the specified format string. The format string is passed tostd.format.formattedRead, and therefore must conform to the format string specification outlined instd.format.
Parameters:
Typesthe types that each of the elements in the line should be returned as
stringfilenamethe name of the file to read
const(char)[]formatthe format string to use when reading
Returns:
If only one type is passed, then an array of that type. Otherwise, an array ofstd.typecons.Tuples.
Throws:
Exception if the format string is malformed. Also, throwsException if any of the lines in the file are not fully consumed by the call tostd.format.formattedRead. Meaning that no empty lines or lines with extra characters are allowed.
Examples:
import std.typecons : tuple;scope(exit){assert(exists(deleteme));    remove(deleteme);}write(deleteme,"12 12.25\n345 1.125");// deleteme is the name of a temporary file// Load file; each line is an int followed by comma, whitespace and a// double.auto a =slurp!(int,double)(deleteme,"%s %s");writeln(a.length);// 2writeln(a[0]);// tuple(12, 12.25)writeln(a[1]);// tuple(345, 1.125)
@trusted stringtempDir();
Returns the path to a directory for temporary files.On POSIX platforms, it searches through the following list of directoriesand returns the first one which is found to exist:
  1. The directory given by theTMPDIR environment variable.
  2. The directory given by theTEMP environment variable.
  3. The directory given by theTMP environment variable.
  4. /tmp/
  5. /var/tmp/
  6. /usr/tmp/
On all platforms,tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures describedbelow will only be performed the first time the function is called. Allsubsequent runs will return the same string, regardless of whetherenvironment variables and directory structures have changed in themeantime.
The POSIXtempDir algorithm is inspired by Python'stempfile.tempdir.
Returns:
On Windows, this function returns the result of calling the Windows API functionGetTempPath.
On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:
  1. The directory given by theTMPDIR environment variable.
  2. The directory given by theTEMP environment variable.
  3. The directory given by theTMP environment variable.
  4. /tmp
  5. /var/tmp
  6. /usr/tmp
On all platforms,tempDir returns"." on failure, representing the current working directory.
Examples:
import std.ascii : letters;import std.conv : to;import std.path : buildPath;import std.random : randomSample;import std.utf : byCodeUnit;// random id with 20 lettersauto id = letters.byCodeUnit.randomSample(20).to!string;auto myFile =tempDir.buildPath(id ~"my_tmp_file");scope(exit) myFile.remove;myFile.write("hello");writeln(myFile.readText);// "hello"
@safe ulonggetAvailableDiskSpace(scope const(char)[]path);
Returns the available disk space based on a given path.On Windows,path must be a directory; on POSIX systems, it can be a file or directory.
Parameters:
const(char)[]pathon Windows, it must be a directory; on POSIX it can be a file or directory
Returns:
Available space in bytes
Throws:
FileException in case of failure
Examples:
import std.exception : assertThrown;auto space =getAvailableDiskSpace(".");assert(space > 0);assertThrown!FileException(getAvailableDiskSpace("ThisFileDoesNotExist123123"));
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 00:53:23 2026

[8]ページ先頭

©2009-2026 Movatter.jp