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[] message);
- Constructor taking the name of the file where error happened and a
message describing the error.
this(in char[] name, uint errno = GetLastError);
- Constructor taking the name of the file where error happened and the
error number (GetLastError in Windows, getErrno in
Posix).
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.
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);
- Get creation/access/modified times of file name.
Throws:
FileException on error.
d_time
lastModified(in char[]
name);
- Returns the time of the last modification of file name. If the
file does not exist, throws a FileException.
d_time
lastModified(in char[]
name, d_time
returnIfMissing);
- Returns the time of the last modification of file name. 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 d_time.min default
makes a non-existing target seem infinitely old so the test
correctly prompts building it.
if (lastModified(source) >= lastModified(target, d_time.min))
{
}
else
{
}
bool
exists(in char[]
name);
- Does file (or directory) name exist?
uint
getAttributes(in char[]
name);
- Get file name attributes.
Throws:
FileException on error.
bool
isdir(in char[]
name);
- Is name a directory?
Throws:
FileException if name doesn't exist.
bool
isfile(in char[]
name);
- Is name a file?
Throws:
FileException if name doesn't exist.
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.
- Directory Entry
- file or directory name
- size of file in bytes
- time of file creation
- time file was last accessed
- time file was last written to
- Return true if DirEntry is a directory.
- Return !=0 if DirEntry is a file.
void
listdir(in char[]
pathname, bool delegate(DirEntry* de)
callback);
- For each file and directory DirEntry in pathname[],
pass it to the callback delegate.
Note:
This function is being phased out. New code should use dirEntries (see below).
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);
- Set access/modified times of file name.
Throws:
FileException on error.
void
rmdirRecurse(in char[]
pathname);
- Remove directory and all of its content and subdirectories,
recursively.
- 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);
- 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.
Example:
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);
}
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);
- Return contents of directory pathname[].
The names in the contents do not include the pathname.
Throws:
FileException on error
Example:
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);
}
string[]
listdir(in char[]
pathname, in char[]
pattern);
string[]
listdir(in char[]
pathname, RegExp
r);
- Return all the files in the directory and its subdirectories
that match pattern or regular expression r.
Parameters:
char[] pathname |
Directory name |
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. |
Example:
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);
- For each file and directory name in pathname[],
pass it to the callback delegate.
Note:
This function is being phased out. New code should use dirEntries (see below).
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);
}