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 using
a local clone.
std.file
Utilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
| Category | Functions |
|---|---|
| General | exists isDir isFile isSymlink rename thisExePath |
| Directories | chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir |
| Files | append copy read readText remove slurp write |
| Symlinks | symlink readLink |
| Attributes | attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes |
| Timestamp | getTimes getTimesWin setTimes timeLastModified |
| Other | DirEntry FileException PreserveAttributes SpanMode |
See Also:
The official tutorial for an
introduction to working with files in D, module
std.stdio for opening files and manipulating them via handles,
and module std.path for manipulating path strings.
License:
Authors:
Walter Bright,
Andrei Alexandrescu,
Jonathan M Davis
Source std/file.d
- class
FileException: object.Exception; - Exception thrown for file I/O errors.
- immutable uint
errno; - OS error code.
- pure @safe this(in char[]
name, in char[]msg, stringfile= __FILE__, size_tline= __LINE__); - Constructor which takes an error message.Parameters:
char[] nameName of filefor which the error occurred.char[] msgMessage describing the error. string fileThe file where the error occurred. size_t lineThe line where the error occurred. - @trusted this(in char[]
name, uinterrno= .errno, stringfile= __FILE__, size_tline= __LINE__); - Constructor which takes the error number (GetLastError in Windows,
errnoin Posix).Parameters:char[] nameName of filefor which the error occurred.uint errnoThe error number. string fileThe file where the error occurred. Defaults to __FILE__. size_t lineThe line where the error occurred. Defaults to __LINE__.
- void[]
read(R)(Rname, size_tupTo= size_t.max)
if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isInfinite!R && !isConvertibleToString!R);
void[]read(R)(auto ref Rname, size_tupTo= size_t.max)
if (isConvertibleToString!R); - Read entire contents of file
nameand returns it as an untyped array. If the file size is larger thanupTo, onlyupTobytes are read.Parameters:R namestring or range of characters representing the file name size_t upToif present, the maximum number of bytes to read Returns:Untyped array of bytes read.Throws:FileException on error.Examples:import std.utf : byChar; scope(exit) { assert(exists(deleteme)); remove(deleteme); } write(deleteme, "1234"); // deleteme is the name of a temporary file writeln(read(deleteme, 2)); // "12" writeln(read(deleteme.byChar)); // "1234" writeln((cast(const(ubyte)[])read(deleteme)).length); // 4
- S
readText(S = string, R)(Rname)
if (isSomeString!S && (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);
SreadText(S = string, R)(auto ref Rname)
if (isConvertibleToString!R); - Read and validates (using std.utf.validate) a text file. S can be a type of array of characters of any width and constancy. No width conversion is performed; if the width of the characters in file
nameis different from the width of elements of S, validation will fail.Parameters:R namestring or range of characters representing the file name Returns:Array of characters read.Throws:FileException on file error, UTFException on UTF decoding error.Examples:import std.exception : enforce; write(deleteme, "abc"); // deleteme is the name of a temporary file scope(exit) remove(deleteme); string content = readText(deleteme); enforce(content == "abc");
- void
write(R)(Rname, const void[]buffer)
if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);
voidwrite(R)(auto ref Rname, const void[]buffer)
if (isConvertibleToString!R); - Write
bufferto filename.Creates the file if it does not already exist.Parameters:R namestring 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 file writeln(cast(int[])read(deleteme)); // a
- void
append(R)(Rname, const void[]buffer)
if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);
voidappend(R)(auto ref Rname, const void[]buffer)
if (isConvertibleToString!R); - Appends
bufferto filename.Creates the file if it does not already exist.Parameters:R namestring 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 file int[] b = [ 13, 21 ]; append(deleteme, b); writeln(cast(int[])read(deleteme)); // a ~ b
- void
rename(RF, RT)(RFfrom, RTto)
if ((isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF) && !isConvertibleToString!RF && (isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT) && !isConvertibleToString!RT);
voidrename(RF, RT)(auto ref RFfrom, auto ref RTto)
if (isConvertibleToString!RF || isConvertibleToString!RT); - Rename file
fromtoto. If the target file exists, it is overwritten.Parameters:RF fromstring or range of characters representing the existing file name RT tostring or range of characters representing the target file name Throws:FileException on error. - void
remove(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidremove(R)(auto ref Rname)
if (isConvertibleToString!R); - Delete file
name.Parameters:R namestring or range of characters representing the file name Throws:FileException on error. - ulong
getSize(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
ulonggetSize(R)(auto ref Rname)
if (isConvertibleToString!R); - Get size of file
namein bytes.Parameters:R namestring or range of characters representing the file name Throws:FileException on error (e.g., file not found). - void
getTimes(R)(Rname, out SysTimeaccessTime, out SysTimemodificationTime)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidgetTimes(R)(auto ref Rname, out SysTimeaccessTime, out SysTimemodificationTime)
if (isConvertibleToString!R); - Get the access and modified times of file or folder
name.Parameters:R nameFile/Folder name to get times for. SysTime accessTimeTime the file/folder was last accessed. SysTime modificationTimeTime the file/folder was last modified. Throws:FileException on error. - void
getTimesWin(R)(Rname, out SysTimefileCreationTime, out SysTimefileAccessTime, out SysTimefileModificationTime)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R); - This function is Windows-Only.Get creation/access/modified times of file
name. This is the same as getTimes except that it also gives you the file creation time - which isn't possible on Posix systems.Parameters:R nameFile name to get times for. SysTime fileCreationTimeTime the file was created. SysTime fileAccessTimeTime the file was last accessed. SysTime fileModificationTimeTime the file was last modified. Throws:FileException on error. - void
setTimes(R)(Rname, SysTimeaccessTime, SysTimemodificationTime)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidsetTimes(R)(auto ref Rname, SysTimeaccessTime, SysTimemodificationTime)
if (isConvertibleToString!R); - Set access/modified times of file or folder
name.Parameters:R nameFile/Folder name to get times for. SysTime accessTimeTime the file/folder was last accessed. SysTime modificationTimeTime the file/folder was last modified. Throws:FileException on error. - SysTime
timeLastModified(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
SysTimetimeLastModified(R)(auto ref Rname)
if (isConvertibleToString!R); - Returns the time that the given file was last modified.Throws:FileException if the given file does not exist.
- SysTime
timeLastModified(R)(Rname, SysTimereturnIfMissing)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R)); - Returns the time that the given file was last modified. If the file does not exist, returns
returnIfMissing.A frequent usage pattern occurs in build automation tools such as make or ant. To check whether file target must be rebuilt from file source (i.e., target is older than source or does not exist), use the comparison below. The code throws a FileException if source does not exist (as it should). On the other hand, the SysTime.min default makes a non-existing target seem infinitely old so the test correctly prompts building it.Parameters:R nameThe name of the file to get the modification time for. SysTime returnIfMissingThe time to return if the given file does not exist. Example
if (timeLastModified(source) >= timeLastModified(target, SysTime.min)) { // must (re)build } else { // target is up-to-date }
- bool
exists(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
boolexists(R)(auto ref Rname)
if (isConvertibleToString!R); - Determine whether the given file (or directory) exists.Parameters:
R namestring or range of characters representing the file name Returns:trueif the file name specified as input exists - uint
getAttributes(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!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 the st_mode value which is part of the stat struct gotten by calling the stat 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:
R nameThe file to get the attributes of. Throws:FileException on error. - uint
getLinkAttributes(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!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 is not a symbolic link, then this function returns the same result as getAttributes.On Windows,
getLinkAttributesis 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:R nameThe file to get the symbolic link attributes of. Returns:the attributesThrows:FileException on error. - void
setAttributes(R)(Rname, uintattributes)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidsetAttributes(R)(auto ref Rname, uintattributes)
if (isConvertibleToString!R); - Set the attributes of the given file.Parameters:
R namethe file name uint attributesthe attributes to set the file to Throws:FileException if the given file does not exist. - @property bool
isDir(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
@property boolisDir(R)(auto ref Rname)
if (isConvertibleToString!R); - Returns whether the given file is a directory.Parameters:
R nameThe path to the file. Returns:trueifnamespecifies a directoryThrows:FileException if the given file does not exist.Example
assert(!"/etc/fonts/fonts.conf".isDir); assert("/usr/share/include".isDir);
- pure nothrow @nogc @safe bool
attrIsDir(uintattributes); - Returns whether the given file attributes are for a directory.Parameters:
uint attributesThe file attributes. Returns:trueifattributesspecifies a directoryExample
assert(!attrIsDir(getAttributes("/etc/fonts/fonts.conf"))); assert(!attrIsDir(getLinkAttributes("/etc/fonts/fonts.conf")));
- @property bool
isFile(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!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, either
isFileor isDir will returntruefor any given file. On Posix systems, ifisFileistrue, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for bothisFileand isDir to befalsefor a particular file (in which case, it's a special file). You can use getAttributes to get the attributes to figure out what type of special it is, or you can use DirEntry to get at its statBuf, which is the result from stat. In either case, see the man page for stat for more information.Parameters:R nameThe path to the file. Returns:trueifnamespecifies a fileThrows:FileException if the given file does not exist.Example
assert("/etc/fonts/fonts.conf".isFile); assert(!"/usr/share/include".isFile);
- pure nothrow @nogc @safe bool
attrIsFile(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, either
attrIsFileor attrIsDir will returntruefor the attributes of any given file. On Posix systems, ifattrIsFileistrue, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for bothattrIsFileand attrIsDir to befalsefor 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 for stat for more information).Parameters:uint attributesThe file attributes. Returns:trueif the given file attributes are for a fileExample
assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf"))); assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));
- @property bool
isSymlink(R)(Rname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
@property boolisSymlink(R)(auto ref Rname)
if (isConvertibleToString!R); - Returns whether the given file is a symbolic link.On Windows, returns
truewhen the file is either a symbolic link or a junction point.Parameters:R nameThe path to the file. Returns:trueifnameis a symbolic linkThrows:FileException if the given file does not exist. - pure nothrow @nogc @safe bool
attrIsSymlink(uintattributes); - Returns whether the given file
attributesare for a symbolic link.On Windows, returntruewhen the file is either a symbolic link or a junction point.Parameters:uint attributesThe file attributes.Returns:trueifattributesare for a symbolic linkExample
core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink"); assert(!getAttributes("/tmp/alink").isSymlink); assert(getLinkAttributes("/tmp/alink").isSymlink);
- void
chdir(R)(Rpathname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidchdir(R)(auto ref Rpathname)
if (isConvertibleToString!R); - Change directory to
pathname.Throws:FileException on error. - void
mkdir(R)(Rpathname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidmkdir(R)(auto ref Rpathname)
if (isConvertibleToString!R); - Make directory
pathname.Throws:FileException on Posix or WindowsException on Windows if an error occured. - @safe void
mkdirRecurse(in char[]pathname); - Make directory and all parent directories as needed.Does nothing if the directory specified by
pathnamealready exists.Throws:FileException on error. - void
rmdir(R)(Rpathname)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
voidrmdir(R)(auto ref Rpathname)
if (isConvertibleToString!R); - Remove directory
pathname.Parameters:R pathnameRange or string specifying the directory name Throws:FileException on error. - void
symlink(RO, RL)(ROoriginal, RLlink)
if ((isInputRange!RO && !isInfinite!RO && isSomeChar!(ElementEncodingType!RO) || isConvertibleToString!RO) && (isInputRange!RL && !isInfinite!RL && isSomeChar!(ElementEncodingType!RL) || isConvertibleToString!RL)); - This function is Posix-Only.Creates a symbolic link (symlink).Parameters:
RO originalThe 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. RL linkThe symlink to create. A relative path is relative to the current working directory. Throws:FileException on error (which includes if the symlink already exists). - string
readLink(R)(Rlink)
if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!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.
- string
getcwd(); - Get the current working directory.Throws:FileException on error.
- @trusted string
thisExePath(); - Returns the full path of the current executable.Throws:
- struct
DirEntry; - Info on a file, similar to what you'd get from stat on a Posix system.
- @safe this(string
path); - Constructs a DirEntry for the given file (or directory).Parameters:
string pathThe file (or directory) to get a DirEntry for. Throws:FileException if the file does not exist. - const @property @safe string
name(); - Returns the path to the file represented by this DirEntry.
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 bool
isDir(); - Returns whether the file represented by this DirEntry 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 bool
isFile(); - Returns whether the file represented by this DirEntry is a file.On Windows, if a file is not a directory, then it's a file. So, either
isFileor isDir will returntrue. On Posix systems, ifisFileistrue, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for bothisFileand isDir to befalsefor a particular file (in which case, it's a special file). You can use attributes or statBuf 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 bool
isSymlink(); - Returns whether the file represented by this DirEntry is a symbolic link.On Windows, return
truewhen the file is either a symbolic link or a junction point. - @property @safe ulong
size(); - Returns the
sizeof the the file represented by this DirEntry in bytes. - const @property @safe SysTime
timeCreated(); - This function is Windows-Only.Returns the creation time of the file represented by this DirEntry.
- @property @safe SysTime
timeLastAccessed(); - Returns the time that the file represented by this DirEntry 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 that
timeLastAccessedwill return the same value as timeLastModified. - @property @safe SysTime
timeLastModified(); - Returns the time that the file represented by this DirEntry was last modified.
- @property @safe uint
attributes(); - Returns the attributes of the file represented by this DirEntry.Note that the file attributes on Windows and Posix systems are completely different. On, Windows, they're what is returned by GetFileAttributes GetFileAttributes Whereas, an Posix systems, they're the st_mode value which is part of the stat struct gotten by calling stat. On Posix systems, if the file represented by this DirEntry is a symbolic link, then attributes are the attributes of the file pointed to by the symbolic link.
- @property @safe uint
linkAttributes(); - On Posix systems, if the file represented by this DirEntry is a symbolic link, then
linkAttributesare the attributes of the symbolic link itself. Otherwise,linkAttributesis identical to attributes.On Windows,linkAttributesis identical to attributes. It exists on Windows so that you don't have to special-case code for Windows when dealing with symbolic links. - @property @safe stat_t
statBuf(); - This function is Posix-Only.The stat struct gotten from calling stat.
- PreserveAttributes
preserveAttributesDefault; - Defaults to Yes.preserveAttributes on Windows, and the opposite on all other platforms.
- void
copy(RF, RT)(RFfrom, RTto, PreserveAttributespreserve= preserveAttributesDefault)
if (isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) && !isConvertibleToString!RF && isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) && !isConvertibleToString!RT);
voidcopy(RF, RT)(auto ref RFfrom, auto ref RTto, PreserveAttributespreserve= preserveAttributesDefault)
if (isConvertibleToString!RF || isConvertibleToString!RT); - Copy file
fromto fileto. File timestamps are preserved. File attributes are preserved, ifpreserveequals Yes.preserveAttributes. On Windows only Yes.preserveAttributes (the default on Windows) is supported. If the target file exists, it is overwritten.Parameters:RF fromstring or range of characters representing the existing file name RT tostring or range of characters representing the target file name PreserveAttributes preservewhether topreserve the file attributesThrows:FileException on error. - void
rmdirRecurse(in char[]pathname); - Remove directory and all of its content and subdirectories, recursively.Throws:FileException if there is an error (including if the given file is not a directory).
- void
rmdirRecurse(ref DirEntryde);
voidrmdirRecurse(DirEntryde); - Remove directory and all of its content and subdirectories, recursively.Throws:FileException if there is an error (including if the given file is not a directory).
- enum
SpanMode: int; - Dictates directory spanning policy for dirEntries (see below).
shallow- Only spans one directory.
depth- Spans the directory in depth-first post-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 in depth-first pre-order, i.e. the content of any subdirectory is spanned right after that subdirectory itself.Note that SpanMode.
breadthwill not result in all directory members occurring before any subdirectory members, i.e. it is not true breadth-first traversal.
- auto
dirEntries(stringpath, SpanModemode, boolfollowSymlink= true);
autodirEntries(stringpath, stringpattern, SpanModemode, boolfollowSymlink= true); - 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 path.Parameters:
string pathThe directory to iterate over. If empty, the current directory will be iterated. string patternOptional 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. SpanMode modeWhether the directory's sub-directories should be iterated in depth-first port-order (depth), depth-first pre-order (breadth), or not at all (shallow). bool followSymlinkWhether symbolic links which point to directories should be treated as directories and their contents iterated over. 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); std.process.system(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);
Examples:Duplicate functionality of D1's std.file.listdir():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!(a => std.path.baseName(a.name)) .array; } void main(string[] args) { import std.stdio; string[] files = listdir(args[1]); writefln("%s", files); } - Select!(Types.length == 1, Types[0][], Tuple!Types[])
slurp(Types...)(stringfilename, in char[]format); - Reads a file line by line and parses the line into a single value or a std.typecons.Tuple of values depending on the length of Types. The lines are parsed using the specified
formatstring. Theformatstring is passed to std.format.formattedRead, and therefore must conform to the format string specification outlined in std.format.Parameters:Types the types that each of the elements in the line should be returned as string filenamethe name of the file to read char[] formatthe format string to use when reading Returns:If only one type is passed, then an array of that type. Otherwise, an array of std.typecons.Tuples.Throws:Exception if theformatstring is malformed. Also, throws Exception if any of the lines in the file are not fully consumed by the call to std.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); // 2 writeln(a[0]); // tuple(12, 12.25) writeln(a[1]); // tuple(345, 1.125)
- @trusted string
tempDir(); - Returns the path to a directory for temporary files.On Windows, this function returns the result of calling the Windows API function GetTempPath. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:
- The directory given by the TMPDIR environment variable.
- The directory given by the TEMP environment variable.
- The directory given by the TMP environment variable.
- /tmp
- /var/tmp
- /usr/tmp
tempDirreturns "." on failure, representing the current working directory. The return value of the function is cached, so the procedures described above will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime. The POSIXtempDiralgorithm is inspired by Python's tempfile.tempdir.
Copyright © 1999-2018 by the D Language Foundation | Page generated by
Ddoc on (no date time)