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
class
FileException: object.Exception;
- Exception thrown for file I/O errors.
- OS error code.
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. |
this(in char[] name, uint errno = GetLastError, string file = __FILE__, size_t line = __LINE__);
- Constructor which takes the error number (GetLastError
in Windows, getErrno in Posix).
Parameters:
char[] name |
Name of file for which the error occurred. |
msg |
Message describing the error. |
string file |
The file where the error occurred. |
size_t line |
The line where the error occurred. |
void[]
read(in char[]
name, size_t
upTo = (uint).max);
- 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.
Example:
import std.file, std.stdio;
void main()
{
auto bytes = cast(ubyte[]) read("filename", 5);
if (bytes.length == 5)
writefln("The fifth byte of the file is 0x%x", bytes[4]);
}
Returns:
Untyped array of bytes read.
Throws:
FileException on error.
S
readText(S = string)(in char[]
name);
- 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.
Returns:
Array of characters read.
Throws:
FileException on file error, UtfException on UTF
decoding error.
Example:
enforce(system("echo abc>deleteme") == 0);
scope(exit) remove("deleteme");
enforce(chomp(readText("deleteme")) == "abc");
void
write(in char[]
name, const void[]
buffer);
- Write buffer to file name.
Throws:
FileException on error.
Example:
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
assert(cast(int[]) read("filename") == a);
}
void
append(in char[]
name, in void[]
buffer);
- Appends buffer to file name.
Throws:
FileException on error.
Example:
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
int[] b = [ 13, 21 ];
append("filename", b);
assert(cast(int[]) read("filename") == a ~ b);
}
void
rename(in char[]
from, in char[]
to);
- Rename file from to to.
Throws:
FileException on error.
void
remove(in char[]
name);
- Delete file name.
Throws:
FileException on error.
ulong
getSize(in char[]
name);
- Get size of file name in bytes.
Throws:
FileException on error (e.g., file not found).
void
getTimes(in char[]
name, out d_time
ftc, out d_time
fta, out d_time
ftm);
- Scheduled for deprecation. Please use getTimesWin (for Windows)
or getTimesPosix (for Posix) instead.
void
getTimesWin(in char[]
name, out SysTime
fileCreationTime, out SysTime
fileAccessTime, out SysTime
fileModificationTime);
- This function is Windows-Only.
Get creation/access/modified times of file name.
Note that the Windows and Posix versions of getTimesX differ
because Posix has no file creation time whereas Windows
has no file status changed time.
Parameters:
char[] 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.
d_time
lastModified(in char[]
name);
- Scheduled for deprecation. Please use
std.file.timeLastModified instead.
d_time
lastModified(in char[]
name, d_time
returnIfMissing);
- Scheduled for deprecation. Please use timeLastModified instead.
SysTime
timeLastModified(in char[]
name);
- Returns the time that the given file was last modified.
Throws:
FileException if the given file does not exist.
SysTime
timeLastModified(in char[]
name, SysTime
returnIfMissing);
- 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:
char[] 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))
{
}
else
{
}
bool
exists(in char[]
name);
- Returns whether the given file (or directory) exists.
uint
getAttributes(in char[]
name);
- 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:
char[] name |
The file to get the attributes of. |
uint
getLinkAttributes(in char[]
name);
- 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:
char[] name |
The file to get the symbolic link attributes of. |
Throws:
FileException on error.
bool
isDir(in char[]
name);
- Returns whether the given file is a directory.
Parameters:
char[] name |
The path to the file. |
Throws:
FileException if the given file does not exist.
Examples:
assert(!"/etc/fonts/fonts.conf".isDir);
assert("/usr/share/include".isDir);
nothrow bool
isDir(uint
attributes);
- Returns whether the given file attributes are for a directory.
Parameters:
uint attributes |
The file attributes. |
Examples:
assert(!getAttributes("/etc/fonts/fonts.conf").isDir);
assert(!getLinkAttributes("/etc/fonts/fonts.conf").isDir);
- Scheduled for deprecation. Please use isDir instead.
bool
isFile(in char[]
name);
- 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 stat man page for more details.
Parameters:
char[] name |
The path to the file. |
Throws:
FileException if the given file does not exist.
Examples:
assert("/etc/fonts/fonts.conf".isFile);
assert(!"/usr/share/include".isFile);
nothrow bool
isFile(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 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). If a file is a special
file, you can use the attributes to check what type of special
file it is (see the stat man page for more information).
Parameters:
uint attributes |
The file attributes. |
Examples:
assert(getAttributes("/etc/fonts/fonts.conf").isFile);
assert(getLinkAttributes("/etc/fonts/fonts.conf").isFile);
- Scheduled for deprecation. Please use isFile instead.
Same is isFile.
bool
isSymLink(in char[]
name);
- Returns whether the given file is a symbolic link.
Always return false on Windows. It exists on Windows so that you don't
have to special-case code for Windows when dealing with symbolic links.
Parameters:
char[] name |
The path to the file. |
Throws:
FileException if the given file does not exist.
nothrow bool
isSymLink(uint
attributes);
- Returns whether the given file attributes are for a symbolic link.
Always return false on Windows. It exists on Windows so that you don't
have to special-case code for Windows when dealing with symbolic links.
Parameters:
uint attributes |
The file attributes. |
Examples:
core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink");
assert(!getAttributes("/tmp/alink").isSymLink);
assert(getLinkAttributes("/tmp/alink").isSymLink);
void
chdir(in char[]
pathname);
- Change directory to pathname.
Throws:
FileException on error.
void
mkdir(in char[]
pathname);
- Make directory pathname.
Throws:
FileException on error.
void
mkdirRecurse(in char[]
pathname);
- Make directory and all parent directories as needed.
void
rmdir(in char[]
pathname);
- Remove directory pathname.
Throws:
FileException on error.
- Get current directory.
Throws:
FileException on error.
- Info on a file, similar to what you'd get from stat on a Posix system.
A DirEntry is obtained by using the functions dirEntry (to get the DirEntry
for a specific file) or dirEntries (to get a DirEntry for each file/directory
in a particular directory).
- 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");
- 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);
- Scheduled for deprecation. Please use isDir instead.
Same as isdir.
- 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);
- Scheduled for deprecation. Please use isFile instead.
Same as isfile.
- Returns whether the file represented by this DirEntry is a symbol link.
Always return false on Windows. It exists on Windows so that you don't
have to special-case code for Windows when dealing with symbolic links.
- Returns the size of the the file represented by this DirEntry in bytes.
const d_time
creationTime();
- Scheduled for deprecation. Please use timeCreated instead.
Returns the creation time of the file represented by this DirEntry.
Note that this property has existed for both Windows and Posix systems
but that it is incorrect on Posix systems. Posix systems do not have
access to the creation time of a file. On Posix systems this property
has incorrectly been the time that the file's status status last changed.
If you want that value, use timeStatusChanged.
const SysTime
timeCreated();
- This function is Windows-Only.
Returns the creation time of the file represented by this DirEntry.
SysTime
timeStatusChanged();
- This function is Posix-Only.
Returns the last time that the status of file represented by this DirEntry
was changed (i.e. owner, group, link count, mode, etc.).
- Scheduled for deprecation. Please use timeLastAccessed instead.
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 lastAccessTime will
return the same value as lastWriteTime.
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 timeLastAccessed will
return the same value as timeLastModified.
- Scheduled for deprecation. Please use timeLastAccessed instead.
Returns the time that the file represented by this DirEntry was last modified.
SysTime
timeLastModified();
- Returns the time that the file represented by this DirEntry was last modified.
- 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.
- On Posix systems, if the file represented by this DirEntry is a symbolic link,
then linkAttributes are the attributes of the symbolic link itself. Otherwise,
linkAttributes is identical to attributes.
On Windows, linkAttributes is identical to attributes. It exists on
Windows so that you don't have to special-case code for Windows when dealing
with symbolic links.
- This function is Posix-Only.
The stat struct gotten from calling stat.
void
listdir(in char[]
pathname, bool delegate(DirEntry* de)
callback);
- Scheduled for deprecation. Please use dirEntries instead.
For each file and directory DirEntry in pathname[],
pass it to the callback delegate.
Parameters:
bool delegate(DirEntry* de) callback |
Delegate that processes each
DirEntry in turn. Returns true to
continue, false to stop. |
Example:
This program lists all the files in its
path argument and all subdirectories thereof.
import std.stdio;
import std.file;
void main(string[] args)
{
bool callback(DirEntry* de)
{
if(de.isDir)
listdir(de.name, &callback);
else
writefln(de.name);
return true;
}
listdir(args[1], &callback);
}
void
copy(in char[]
from, in char[]
to);
- Copy file from to file to. File timestamps are preserved.
void
setTimes(in char[]
name, d_time
fta, d_time
ftm);
- Scheduled for deprecation. Please use the version which takes
std.datetime.SysTime instead.
Set access/modified times of file name.
Throws:
FileException on error.
void
setTimes(in char[]
name, SysTime
fileAccessTime, SysTime
fileModificationTime);
- Set access/modified times of file name.
Parameters:
SysTime fileAccessTime |
Time the file was last accessed. |
SysTime fileModificationTime |
Time the file was last modified. |
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);
- 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).
- Dictates directory spanning policy for dirEntries (see below).
- Only spans one directory.
- Spans the directory depth-first, i.e. the content of any
subdirectory is spanned before that subdirectory itself. Useful
e.g. when recursively deleting files.
- Spans the directory breadth-first, i.e. the content of any
subdirectory is spanned right after that subdirectory itself.
DirIterator
dirEntries(string
path, SpanMode
mode, bool
followSymLinks = true);
- Iterates a directory using foreach. 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 directory entry
includes the path prefix.
Parameters:
string path |
The directory to iterato 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 followSymLinks |
Whether symbolic links which point to directories
should be treated as directories and their contents
iterated over. Ignored on Windows. |
Examples:
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
foreach (string name; dirEntries(".", SpanMode.breadth))
{
writeln(name);
}
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
DirEntry
dirEntry(in char[]
name);
- Returns a DirEntry for the given file (or directory).
Parameters:
char[] name |
The file (or directory) to get a DirEntry for. |
Throws:
FileException) if the file does not exist.
Select!(Types.length == 1,Types[0][],Tuple!(Types)[])
slurp(Types...)(string
filename, in char[]
format);
- Reads an entire file into an array.
Example:
auto a = slurp!(int, double)("filename", "%s, %s");
string[]
listDir(in char[]
pathname);
- Returns the contents of the given directory.
The names in the contents do not include the pathname.
Throws:
FileException on error.
Examples:
This program lists all the files and subdirectories in its
path argument.
import std.stdio;
import std.file;
void main(string[] args)
{
auto dirs = std.file.listdir(args[1]);
foreach(d; dirs)
writefln(d);
}
- Scheduled for deprecation. Please use listDir instead.
Same is listDir.
string[]
listDir(in char[]
pathname, in char[]
pattern, bool
followSymLinks = true);
string[]
listDir(in char[]
pathname, RegExp
r, bool
followSymLinks = true);
- Returns all the files in the directory and its sub-directories
which match pattern or regular expression r.
Parameters:
char[] pathname |
The path of the directory to search. |
char[] pattern |
String with wildcards, such as "*.d". The supported
wildcard strings are described under fnmatch() in
std.path. |
r |
Regular expression, for more powerful pattern matching. |
bool followSymLinks |
Whether symbolic links which point to directories
should be treated as directories and their contents
iterated over. Ignored on Windows. |
Examples:
This program lists all the files with a "d" extension in
the path passed as the first argument.
import std.stdio;
import std.file;
void main(string[] args)
{
auto d_source_files = std.file.listDir(args[1], "*.d");
foreach(d; d_source_files)
writefln(d);
}
A regular expression version that searches for all files with "d" or
"obj" extensions:
import std.stdio;
import std.file;
import std.regexp;
void main(string[] args)
{
auto d_source_files = std.file.listDir(args[1], RegExp(r"\.(d|obj)$"));
foreach(d; d_source_files)
writefln(d);
}
void
listdir(in char[]
pathname, bool delegate(string filename)
callback);
- Scheduled for deprecation. Please use dirEntries instead.
For each file and directory name in pathname[],
pass it to the callback delegate.
Parameters:
bool delegate(string filename) callback |
Delegate that processes each
filename in turn. Returns true to
continue, false to stop. |
Example:
This program lists all the files in its
path argument, including the path.
import std.stdio;
import std.path;
import std.file;
void main(string[] args)
{
auto pathname = args[1];
string[] result;
bool listing(string filename)
{
result ~= std.path.join(pathname, filename);
return true; }
listdir(pathname, &listing);
foreach (name; result)
writefln("%s", name);
}