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
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.
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, string file = __FILE__, size_t line = __LINE__);
- Constructor which takes an error message.Parameters:
char[] name Name of file for which the error occurred. char[] msg Message describing the error. string file The file where the error occurred. size_t line The line where the error occurred. - @trusted this(in char[] name, uint errno = .errno, string file = __FILE__, size_t line = __LINE__);
- Constructor which takes the error number (GetLastError in Windows, errno in Posix).Parameters:
char[] name Name of file for which the error occurred. uint errno The error number. string file The file where the error occurred. Defaults to __FILE__. size_t line The line where the error occurred. Defaults to __LINE__.
- void[] read(R)(R name, size_t upTo = size_t.max) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Read entire contents of file name and returns it as an untyped array. If the file size is larger than upTo, only upTo bytes are read.Parameters:Returns:Untyped array of bytes read.Throws:FileException on error.Examples:
import std.utf : byChar; scope(exit) { assert(exists("someUniqueFilename")); remove("someUniqueFilename"); } write("someUniqueFilename", "1234"); assert(read("someUniqueFilename", 2) == "12"); assert(read("someUniqueFilename".byChar) == "1234"); assert((cast(ubyte[])read("someUniqueFilename")).length == 4);
- S readText(S = string, R)(R name) if (isSomeString!S && (isInputRange!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !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 name is different from the width of elements of S, validation will fail.Parameters:
R name string 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.string; write("someUniqueFilename", "abc\n"); scope(exit) { assert(exists("someUniqueFilename")); remove("someUniqueFilename"); } enforce(chomp(readText("someUniqueFilename")) == "abc");
- void write(R)(R name, const void[] buffer) if ((isInputRange!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);
- Write buffer to file name.Parameters:
R name string or range of characters representing the file name void[] buffer data to be written to file Throws:FileException on error.Examples:scope(exit) { assert(exists("someUniqueFilename")); remove("someUniqueFilename"); } int[] a = [ 0, 1, 1, 2, 3, 5, 8 ]; write("someUniqueFilename", a); assert(cast(int[]) read("someUniqueFilename") == a);
- void append(R)(R name, const void[] buffer) if ((isInputRange!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && !isConvertibleToString!R);
- Appends buffer to file name.Parameters:
R name string or range of characters representing the file name void[] buffer data to be appended to file Throws:FileException on error.Examples:scope(exit) { assert(exists("someUniqueFilename")); remove("someUniqueFilename"); } int[] a = [ 0, 1, 1, 2, 3, 5, 8 ]; write("someUniqueFilename", a); int[] b = [ 13, 21 ]; append("someUniqueFilename", b); assert(cast(int[]) read("someUniqueFilename") == a ~ b);
- void rename(RF, RT)(RF from, RT to) if ((isInputRange!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF) && !isConvertibleToString!RF && (isInputRange!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT) && !isConvertibleToString!RT);
- Rename file from to to. If the target file exists, it is overwritten.Parameters:
RF from string or range of characters representing the existing file name RT to string or range of characters representing the target file name Throws:FileException on error. - void remove(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Delete file name.Parameters:
R name string or range of characters representing the file name Throws:FileException on error. - ulong getSize(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Get size of file name in bytes.Parameters:
R name string or range of characters representing the file name Throws:FileException on error (e.g., file not found). - void getTimes(R)(R name, out SysTime accessTime, out SysTime modificationTime) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Get the access and modified times of file or folder name.Parameters:
R name File/Folder name to get times for. SysTime accessTime Time the file/folder was last accessed. SysTime modificationTime Time the file/folder was last modified. Throws:FileException on error. - void getTimesWin(R)(R name, out SysTime fileCreationTime, out SysTime fileAccessTime, out SysTime fileModificationTime) if (isInputRange!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 name File name to get times for. SysTime fileCreationTime Time the file was created. SysTime fileAccessTime Time the file was last accessed. SysTime fileModificationTime Time the file was last modified. Throws:FileException on error. - @safe void setTimes(R)(R name, SysTime accessTime, SysTime modificationTime) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Set access/modified times of file or folder name.Parameters:
R name File/Folder name to get times for. SysTime accessTime Time the file/folder was last accessed. SysTime modificationTime Time the file/folder was last modified. Throws:FileException on error. - SysTime timeLastModified(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Returns the time that the given file was last modified.Throws:FileException if the given file does not exist.
- SysTime timeLastModified(R)(R name, SysTime returnIfMissing) if (isInputRange!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 name The name of the file to get the modification time for. SysTime returnIfMissing The time to return if the given file does not exist. Examples:if(timeLastModified(source) >= timeLastModified(target, SysTime.min)) { // must (re)build } else { // target is up-to-date }
- bool exists(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
-
Parameters:
R name string or range of characters representing the file name - uint getAttributes(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !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 name The file to get the attributes of. Throws:FileException on error. - uint getLinkAttributes(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !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, 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:
R name The file to get the symbolic link attributes of. Returns:the attributesThrows:FileException on error. - void setAttributes(R)(R name, uint attributes) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Set the attributes of the given file.Parameters:
R name the file name uint attributes the attributes to set the file to Throws:FileException if the given file does not exist. - @property bool isDir(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Returns whether the given file is a directory.Parameters:
R name The path to the file. Returns:true if the name specifies a directoryThrows:FileException if the given file does not exist.Examples:assert(!"/etc/fonts/fonts.conf".isDir); assert("/usr/share/include".isDir);
- pure nothrow @nogc @safe bool attrIsDir(uint attributes);
- Returns whether the given file attributes are for a directory.Parameters:
uint attributes The file attributes. Returns:true if attibutes specifies a directoryExamples:assert(!attrIsDir(getAttributes("/etc/fonts/fonts.conf"))); assert(!attrIsDir(getLinkAttributes("/etc/fonts/fonts.conf")));
- @property bool isFile(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !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 isFile or isDir will return true for any given file. On Posix systems, if isFile is true, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for both isFile and isDir to be false for 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 name The path to the file. Returns:true if name specifies a fileThrows:FileException if the given file does not exist.Examples:assert("/etc/fonts/fonts.conf".isFile); assert(!"/usr/share/include".isFile);
- pure nothrow @nogc @safe bool attrIsFile(uint attributes);
- 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 attrIsFile or attrIsDir will return true for the attributes of any given file. On Posix systems, if attrIsFile is true, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for both attrIsFile and attrIsDir to be false 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 for stat for more information).Parameters:
uint attributes The file attributes. Returns:true if the given file attributes are for a fileExamples:assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf"))); assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));
- @property bool isSymlink(R)(R name) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Returns whether the given file is a symbolic link.On Windows, returns true when the file is either a symbolic link or a junction point.Parameters:
R name The path to the file. Returns:true if name is a symbolic linkThrows:FileException if the given file does not exist. - pure nothrow @nogc @safe bool attrIsSymlink(uint attributes);
- Returns whether the given file attributes are for a symbolic link.On Windows, return true when the file is either a symbolic link or a junction point.Parameters:
uint attributes The file attributes. Returns:true if attributes are for a symbolic linkExamples:core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink"); assert(!getAttributes("/tmp/alink").isSymlink); assert(getLinkAttributes("/tmp/alink").isSymlink);
- void chdir(R)(R pathname) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Change directory to pathname.Throws:FileException on error.
- void mkdir(R)(R pathname) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Make directory pathname.Throws:FileException on Posix or WindowsException on Windows if an error occured.
- void mkdirRecurse(in char[] pathname);
- Make directory and all parent directories as needed.Throws:FileException on error.
- void rmdir(R)(R pathname) if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isConvertibleToString!R);
- Remove directory pathname.Parameters:
R pathname Range or string specifying the directory name Throws:FileException on error. - @safe void symlink(C1, C2)(const(C1)[] original, const(C2)[] link);
- This function is Posix-Only.
Note: Relative paths are relative to the current working directory, not the files being linked to or from.
- @safe string readLink(C)(const(C)[] link);
- 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.
- this(string path);
- Constructs a DirEntry for the given file (or directory).Parameters:
string path The file (or directory) to get a DirEntry for. Throws:FileException if the file does not exist. - const @property string name();
- Returns the path to the file represented by this DirEntry.Examples:
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 bool isDir();
- Returns whether the file represented by this DirEntry is a directory.Examples:
auto de1 = DirEntry("/etc/fonts/fonts.conf"); assert(!de1.isDir); auto de2 = DirEntry("/usr/share/include"); assert(de2.isDir);
- @property 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 isFile or isDir will return true. On Posix systems, if isFile is true, that indicates that the file is a regular file (e.g. not a block not device). So, on Posix systems, it's possible for both isFile and isDir to be false for 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).Examples:
auto de1 = DirEntry("/etc/fonts/fonts.conf"); assert(de1.isFile); auto de2 = DirEntry("/usr/share/include"); assert(!de2.isFile);
- @property bool isSymlink();
- Returns whether the file represented by this DirEntry is a symbolic link.On Windows, return true when the file is either a symbolic link or a junction point.
- @property ulong size();
- const @property SysTime timeCreated();
- This function is Windows-Only.Returns the creation time of the file represented by this DirEntry.
- @property SysTime timeLastAccessed();
- Returns the time that the file represented by this DirEntry was last accessed.
- @property SysTime timeLastModified();
- Returns the time that the file represented by this DirEntry was last modified.
- @property uint attributes();
-
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 uint linkAttributes();
- @property stat_t statBuf();
- This function is Posix-Only.The stat struct gotten from calling stat.
- PreserveAttributes preserveAttributesDefault;
- Defaults to PreserveAttributes.yes on Windows, and the opposite on all other platforms.
- void copy(RF, RT)(RF from, RT to, PreserveAttributes preserve = preserveAttributesDefault) if (isInputRange!RF && isSomeChar!(ElementEncodingType!RF) && !isConvertibleToString!RF && isInputRange!RT && isSomeChar!(ElementEncodingType!RT) && !isConvertibleToString!RT);
- Copy file from to file to. File timestamps are preserved. File attributes are preserved, if preserve equals PreserveAttributes.yes. On Windows only PreserveAttributes.yes (the default on Windows) is supported. If the target file exists, it is overwritten.Parameters:
RF from string or range of characters representing the existing file name RT to string or range of characters representing the target file name Throws: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 DirEntry de);
void rmdirRecurse(DirEntry de); - 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).
- auto dirEntries(string path, SpanMode mode, bool followSymlink = 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 the how the directory is traversed. The name of the each directory entry iterated contains the absolute path.Parameters:
string path The directory to iterate over. SpanMode mode Whether the directory's sub-directories should be iterated over depth-first (depth), breadth-first (breadth), or not at all (shallow). bool followSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over. Throws:FileException if the directory does not exist.Examples:// Iterate a directory in depth foreach (string name; dirEntries("destroy/me", SpanMode.depth)) { remove(name); } // Iterate a 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); }
Examples:Duplicate functionality of D1's std.file.listdir():string[] listdir(string pathname) { import std.file; import std.path; import std.algorithm; import std.array; 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); }
- auto dirEntries(string path, string pattern, SpanMode mode, bool followSymlink = true);
- Convenience wrapper for filtering file names with a glob pattern.Parameters:
string path The directory to iterate over. string pattern String with wildcards, such as "*.d". The supported wildcard strings are described under std.path.globMatch. SpanMode mode Whether the directory's sub-directories should be iterated over depth-first (depth), breadth-first (breadth), or not at all (shallow). bool followSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over. Throws:FileException if the directory does not exist.Examples:// 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);
- Select!(Types.length == 1, Types[0][], Tuple!Types[]) slurp(Types...)(string filename, in char[] format);
- Reads an entire file into an array.Examples:
scope(exit) { assert(exists("someUniqueFilename")); remove("someUniqueFilename"); } write("someUniqueFilename", "12 12.25\n345 1.125"); // Load file; each line is an int followed by comma, whitespace and a // double. auto a = slurp!(int, double)("someUniqueFilename", "%s %s"); assert(a.length == 2); assert(a[0] == tuple(12, 12.25)); assert(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