Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.
If flag KeepTerminator
is set to KeepTerminator.yes
, then the delimiter is included in the strings returned.
Encapsulates a FILE*
. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulating FILE*
values directly is unsafe and error-prone in many ways. The File
type ensures safe manipulation, automatic file closing, and a lot of convenience.
The underlying FILE*
handle is maintained in a reference-counted manner, such that as soon as the last File
variable bound to a given FILE*
goes out of scope, the underlying FILE*
is automatically closed.
// test.d void main(string[] args) { auto f = File("test.txt", "w"); // open for writing f.write("Hello"); if (args.length > 1) { auto g = f; // now g and f write to the same file // internal reference count is 2 g.write(", ", args[1]); // g exits scope, reference count decreases to 1 } f.writeln("!"); // f exits scope, reference count falls to zero, // underlying `FILE*` is closed. }
% rdmd test.d Jimmy % cat test.txt Hello, Jimmy! % _
Constructor taking the name of the file to open and the open mode.
Copying one File
object to another results in the two File
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no File
object refers to it anymore.
string name
| range or string representing the file name |
const(char)[] stdioOpenmode
| range or string represting the open mode (with the same semantics as in the C standard library fopen function) |
ErrnoException
if the file could not be opened.Assigns a file to another. The target of the assignment gets detached from whatever file it was attached to, and attaches itself to the new file.
Detaches from the current file (throwing on failure), and then attempts to open file name
with mode stdioOpenmode
. The mode has the same semantics as in the C standard library fopen function.
ErrnoException
in case of error.Reuses the File
object to either open a different file, or change the file mode. If name
is null
, the mode of the currently open file is changed; otherwise, a new file is opened, reusing the C FILE*
. The function has the same semantics as in the C standard library freopen function.
reopen
with a null
name
is not implemented in all C runtimes. ErrnoException
in case of error.Detaches from the current file (throwing on failure), and then runs a command by calling the C standard library function popen.
ErrnoException
in case of error.First calls detach
(throwing on failure), and then attempts to associate the given file descriptor with the File
. The mode must be compatible with the mode of the file descriptor.
ErrnoException
in case of error.First calls detach
(throwing on failure), and then attempts to associate the given Windows HANDLE
with the File
. The mode must be compatible with the access attributes of the handle. Windows only.
ErrnoException
in case of error.Returns true
if the file is opened.
Returns true
if the file is at end (see feof).
Exception
if the file is not opened.Returns the name of the last opened file, if any. If a File
was created with tmpfile
and wrapFile
it has no name.
If the file is not opened, returns true
. Otherwise, returns ferror for the file handle.
Detaches from the underlying file. If the sole owner, calls close
.
ErrnoException
on failure if closing the file.If the file was unopened, succeeds vacuously. Otherwise closes the file (by calling fclose), throwing on error. Even if an exception is thrown, afterwards the File
object is empty. This is different from detach
in that it always closes the file; consequently, all other File
objects referring to the same handle will see a closed file henceforth.
ErrnoException
on error.If the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.
Flushes the C FILE
buffers.
Calls fflush for the file handle.
Exception
if the file is not opened or if the call to fflush
fails.Forces any data buffered by the OS to be written to disk. Call flush
before calling this function to flush the C FILE
buffers first.
This function calls FlushFileBuffers
on Windows and fsync
on POSIX for the file handle.
Exception
if the file is not opened or if the OS call fails.Calls fread for the file handle. The number of items to read and the size of each item is inferred from the size and type of the input array, respectively.
buffer
containing the data that was actually read. This will be shorter than buffer
if EOF was reached before the buffer could be filled. Exception
if buffer
is empty. ErrnoException
if the file is not opened or the call to fread
fails. rawRead
always reads in binary mode on Windows.static import std.file; auto testFile = std.file.deleteme(); std.file.write(testFile, "\r\n\n\r\n"); scope(exit) std.file.remove(testFile); auto f = File(testFile, "r"); auto buf = f.rawRead(new char[5]); f.close(); writeln(buf); // "\r\n\n\r\n"
Calls fwrite for the file handle. The number of items to write and the size of each item is inferred from the size and type of the input array, respectively. An error is thrown if the buffer could not be written in its entirety.
rawWrite
always writes in binary mode on Windows.
ErrnoException
if the file is not opened or if the call to fwrite
fails.static import std.file; auto testFile = std.file.deleteme(); auto f = File(testFile, "w"); scope(exit) std.file.remove(testFile); f.rawWrite("\r\n\n\r\n"); f.close(); writeln(std.file.read(testFile)); // "\r\n\n\r\n"
Calls fseek for the file handle.
Exception
if the file is not opened. ErrnoException
if the call to fseek
fails.Calls ftell for the managed file handle.
Exception
if the file is not opened. ErrnoException
if the call to ftell
fails.import std.conv : text; static import std.file; auto testFile = std.file.deleteme(); std.file.write(testFile, "abcdefghijklmnopqrstuvwqxyz"); scope(exit) { std.file.remove(testFile); } auto f = File(testFile); auto a = new ubyte[4]; f.rawRead(a); writeln(f.tell); // 4
Calls rewind for the file handle.
Exception
if the file is not opened.Calls setvbuf for the file handle.
Exception
if the file is not opened. ErrnoException
if the call to setvbuf
fails.Calls setvbuf for the file handle.
Exception
if the file is not opened. ErrnoException
if the call to setvbuf
fails.Locks the specified file segment. If the file segment is already locked by another process, waits until the existing lock is released. If both start
and length
are zero, the entire file is locked.
Locks created using lock
and tryLock
have the following properties:
File
will be released as well.Attempts to lock the specified file segment. If both start
and length
are zero, the entire file is locked.
true
if the lock was successful, and false
if the specified file segment was already locked.Removes the lock over the specified file segment.
Writes its arguments in text format to the file.
Exception
if the file is not opened. ErrnoException
on an error writing to the file.Writes its arguments in text format to the file, followed by a newline.
Exception
if the file is not opened. ErrnoException
on an error writing to the file.Writes its arguments in text format to the file, according to the format string fmt.
Char[] fmt
| The format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
A args
| Items to write. |
Exception
if the file is not opened. ErrnoException
on an error writing to the file.Equivalent to file.writef(fmt, args, '\n')
.
Read line from the file handle and return it as a specified type.
This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the File.readln(buf)
version, which may offer better performance as it can reuse its read buffer.
S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to string . |
dchar terminator
| Line terminator (by default, '\n' ). |
StdioException
on I/O error, or UnicodeException
on Unicode conversion error. // Reads `stdin` and writes it to `stdout`. import std.stdio; void main() { string line; while ((line = stdin.readln()) !is null) write(line); }
Read line from the file handle and write it to buf[]
, including terminating character.
This can be faster than line = File.readln()
because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them.
C[] buf
| Buffer used to store the resulting line data. buf is resized as necessary. |
dchar terminator
| Line terminator (by default, '\n' ). Use std.ascii.newline for portability (unless the file was opened in text mode). |
StdioException
on I/O error, or UnicodeException
on Unicode conversion error. // Read lines from `stdin` into a string // Ignore lines starting with '#' // Write the string to `stdout` void main() { string output; char[] buf; while (stdin.readln(buf)) { if (buf[0] == '#') continue; output ~= buf; } write(output); }This method can be more efficient than the one in the previous example because
stdin.readln(buf)
reuses (if possible) memory allocated for buf
, whereas line = stdin.readln()
makes a new memory allocation for every line. For even better performance you can help readln
by passing in a large buffer to avoid memory reallocations. This can be done by reusing the largest buffer returned by readln
: // Read lines from `stdin` and count words void main() { char[] buf; size_t words = 0; while (!stdin.eof) { char[] line = buf; stdin.readln(line); if (line.length > buf.length) buf = line; words += line.split.length; } writeln(words); }This is actually what
byLine
does internally, so its usage is recommended if you want to process a complete file. Reads formatted data from the file using std.format.formattedRead
.
const(char)[] format
| The format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
Data data
| Items to be read. |
// test.d void main() { import std.stdio; auto f = File("input"); foreach (_; 0 .. 3) { int a; f.readf!" %d"(a); writeln(++a); } }
% echo "1 2 3" > input % rdmd test.d 2 3 4
static import std.file; auto deleteme = std.file.deleteme(); std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n"); scope(exit) std.file.remove(deleteme); string s; auto f = File(deleteme); f.readf!"%s\n"(s); writeln(s); // "hello" f.readf("%s\n", s); writeln(s); // "world" bool b1, b2; f.readf("%s\n%s\n", b1, b2); assert(b1 == true && b2 == false);
Returns a temporary file by calling tmpfile. Note that the created file has no name
.
Unsafe function that wraps an existing FILE*
. The resulting File
never takes the initiative in closing the file. Note that the created file has no name
Returns the FILE*
corresponding to this object.
Returns the file number corresponding to this object.
Returns the underlying operating system HANDLE
(Windows only).
Returns an input range set up to read from the file handle one line at a time.
The element type for the range will be Char[]
. Range primitives may throw StdioException
on I/O error.
front
will not persist after popFront
is called, so the caller must copy its contents (e.g. by calling to!string
) when retention is needed. If the caller needs to retain a copy of every line, use the byLineCopy
function instead. Char | Character type for each line, defaulting to char . |
KeepTerminator keepTerminator
| Use Yes.keepTerminator to include the terminator at the end of each line. |
Terminator terminator
| Line separator ('\n' by default). Use std.ascii.newline for portability (unless the file was opened in text mode). |
import std.algorithm, std.stdio, std.string; // Count words in a file using ranges. void main() { auto file = File("file.txt"); // Open for reading const wordCount = file.byLine() // Read lines .map!split // Split into words .map!(a => a.length) // Count words per line .sum(); // Total word count writeln(wordCount); }
import std.range, std.stdio; // Read lines using foreach. void main() { auto file = File("file.txt"); // Open for reading auto range = file.byLine(); // Print first three lines foreach (line; range.take(3)) writeln(line); // Print remaining lines beginning with '#' foreach (line; range) { if (!line.empty && line[0] == '#') writeln(line); } }Notice that neither example accesses the line data returned by
front
after the corresponding popFront
call is made (because the contents may well have changed). Returns an input range set up to read from the file handle one line at a time. Each line will be newly allocated. front
will cache its value to allow repeated calls without unnecessary allocations.
File.byLine.map!idup
. Char[]
. Range primitives may throw StdioException
on I/O error. Char | Character type for each line, defaulting to immutable char . |
KeepTerminator keepTerminator
| Use Yes.keepTerminator to include the terminator at the end of each line. |
Terminator terminator
| Line separator ('\n' by default). Use std.ascii.newline for portability (unless the file was opened in text mode). |
import std.algorithm, std.array, std.stdio; // Print sorted lines of a file. void main() { auto sortedLines = File("file.txt") // Open for reading .byLineCopy() // Read persistent lines .array() // into an array .sort(); // then sort them foreach (line; sortedLines) writeln(line); }
std.file.readText
Creates an input range set up to parse one line at a time from the file into a tuple.
Range primitives may throw StdioException
on I/O error.
string format
| tuple record format |
static import std.file; import std.typecons : tuple; // prepare test file auto testFile = std.file.deleteme(); scope(failure) printf("Failed test at line %d\n", __LINE__); std.file.write(testFile, "1 2\n4 1\n5 100"); scope(exit) std.file.remove(testFile); File f = File(testFile); scope(exit) f.close(); auto expected = [tuple(1, 2), tuple(4, 1), tuple(5, 100)]; uint i; foreach (e; f.byRecord!(int, int)("%s %s")) { writeln(e); // expected[i++] }
Returns an input range set up to read from the file handle a chunk at a time.
The element type for the range will be ubyte[]
. Range primitives may throw StdioException
on I/O error.
void main() { // Read standard input 4KB at a time foreach (ubyte[] buffer; stdin.byChunk(4096)) { ... use buffer ... } }The parameter may be a number (as shown in the example above) dictating the size of each chunk. Alternatively,
byChunk
accepts a user-provided buffer that it uses directly. void main() { // Read standard input 4KB at a time foreach (ubyte[] buffer; stdin.byChunk(new ubyte[4096])) { ... use buffer ... } }In either case, the content of the buffer is reused across calls. That means
front
will not persist after popFront
is called, so if retention is needed, the caller must copy its contents (e.g. by calling buffer.dup
). In the example above, buffer.length
is 4096 for all iterations, except for the last one, in which case buffer.length
may be less than 4096 (but always greater than zero). With the mentioned limitations, byChunk
works with any algorithm compatible with input ranges. // Efficient file copy, 1MB at a time. import std.algorithm, std.stdio; void main() { stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter()); }
std.algorithm.iteration.joiner
can be used to join chunks together into a single range lazily. import std.algorithm, std.stdio; void main() { //Range of ranges static assert(is(typeof(stdin.byChunk(4096).front) == ubyte[])); //Range of elements static assert(is(typeof(stdin.byChunk(4096).joiner.front) == ubyte)); }
byChunk
returns a range initialized with the File
object and the appropriate buffer. Exception
. In case of an I/O error throws StdioException
.Output range which locks the file when created, and unlocks the file when it goes out of scope.
ubyte[]
, individual character types, and individual ubyte
s. char
s or ubyte
s is faster than writing each character individually from a range. For large amounts of data, writing the contents in chunks using an intermediary array can result in a speed increase. std.utf.UTFException
if the data given is a char
range and it contains malformed UTF data. byChunk
for an example.Returns an output range that locks the file and allows fast writing to it.
import std.algorithm, std.range, std.stdio; void main() { enum size = 500; writef("P5\n%d %d %d\n", size, size, ubyte.max); iota(-1, 3, 2.0/size).map!(y => iota(-1.5, 0.5, 2.0/size).map!(x => cast(ubyte)(1+ recurrence!((a, n) => x + y*1i + a[n-1]^^2)(0+0i) .take(ubyte.max) .countUntil!(z => z.re^^2 + z.im^^2 > 4)) ) ) .copy(stdout.lockingBinaryWriter); }
Get the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.
Used to specify the lock type for File.lock
and File.tryLock
.
Specifies a read (shared) lock. A read lock denies all processes write access to the specified region of the file, including the process that first locks the region. All processes can read the locked region. Multiple simultaneous read locks are allowed, as long as there are no exclusive locks.
Specifies a read/write (exclusive) lock. A read/write lock denies all other processes both read and write access to the locked file region. If a segment has an exclusive lock, it may not have any shared locks or other exclusive locks.
Indicates whether T
is a file handle, i.e. the type is implicitly convertable to File
or a pointer to a core.stdc.stdio.FILE
.
true
if T
is a file handle, false
otherwise.static assert(isFileHandle!(FILE*)); static assert(isFileHandle!(File));
Writes its arguments in text format to standard output (without a trailing newline).
T args
| the items to write to stdout
|
StdioException
. stdin
and writes it to stdout
with an argument counter. import std.stdio; void main() { string line; for (size_t count = 0; (line = readln) !is null; count++) { write("Input ", count, ": ", line, "\n"); } }
Equivalent to write(args, '\n')
. Calling writeln
without arguments is valid and just prints a newline to the standard output.
T args
| the items to write to stdout
|
StdioException
. stdin
and writes it to stdout
with a argument counter. import std.stdio; void main() { string line; for (size_t count = 0; (line = readln) !is null; count++) { writeln("Input ", count, ": ", line); } }
Writes formatted data to standard output (without a trailing newline).
Char[] fmt
| The format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
A args
| Items to write. |
writef(stderr, "%s", "message");to print a message to
stderr
. This syntax is no longer supported, and has been superceded by: stderr.writef("%s", "message");
Equivalent to writef(fmt, args, '\n')
.
Reads formatted data from stdin
using std.format.formattedRead
.
const(char)[] format
| The format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. |
A args
| Items to be read. |
// test.d void main() { import std.stdio; foreach (_; 0 .. 3) { int a; readf!" %d"(a); writeln(++a); } }
% echo "1 2 3" | rdmd test.d 2 3 4
Read line from stdin
.
This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the readln(buf)
version, which may offer better performance as it can reuse its read buffer.
S | Template parameter; the type of the allocated buffer, and the type returned. Defaults to string . |
dchar terminator
| Line terminator (by default, '\n' ). |
StdioException
on I/O error, or UnicodeException
on Unicode conversion error. stdin
and writes it to stdout
. import std.stdio; void main() { string line; while ((line = readln()) !is null) write(line); }
Read line from stdin
and write it to buf[], including terminating character.
This can be faster than line = readln()
because you can reuse the buffer for each call. Note that reusing the buffer means that you must copy the previous contents if you wish to retain them.
size_t
0 for end of file, otherwise number of characters read C[] buf
| Buffer used to store the resulting line data. buf is resized as necessary. |
dchar terminator
| Line terminator (by default, '\n' ). Use std.ascii.newline for portability (unless the file was opened in text mode). |
StdioException
on I/O error, or UnicodeException
on Unicode conversion error. stdin
and writes it to stdout
. import std.stdio; void main() { char[] buf; while (readln(buf)) write(buf); }
Convenience function that forwards to core.sys.posix.stdio.popen
with appropriately-constructed C-style strings.
Iterates through the lines of a file by using foreach
.
void main() { foreach (string line; lines(stdin)) { ... use line ... } }The line terminator (
'\n'
by default) is part of the string read (it could be missing in the last line of the file). Several types are supported for line
, and the behavior of lines
changes accordingly: line
has type string
, wstring
, or dstring
, a new string of the respective type is allocated every read.line
has type char[]
, wchar[]
, dchar[]
, the line's content will be reused (overwritten) across reads.line
has type immutable(ubyte)[]
, the behavior is similar to case (1), except that no UTF checking is attempted upon input.line
has type ubyte[]
, the behavior is similar to case (2), except that no UTF checking is attempted upon input.ulong
or uint
) tracks the zero-based number of the current line. foreach (ulong i, string line; lines(stdin)) { ... use line ... }In case of an I/O error, an
StdioException
is thrown. byLine
Constructor.
File f
| File to read lines from. |
dchar terminator
| Line separator ('\n' by default). |
Iterates through a file a chunk at a time by using foreach
.
void main() { foreach (ubyte[] buffer; chunks(stdin, 4096)) { ... use buffer ... } }The content of
buffer
is reused across calls. In the example above, buffer.length
is 4096 for all iterations, except for the last one, in which case buffer.length
may be less than 4096 (but always greater than zero). In case of an I/O error, an StdioException
is thrown. Writes an array or range to a file. Shorthand for data.copy(File(fileName, "wb").lockingBinaryWriter)
. Similar to std.file.write
, strings are written as-is, rather than encoded according to the File
's orientation.
Thrown if I/O errors happen.
Operating system error code.
Initialize with a message and an error code.
Convenience functions that throw an StdioException
.
The standard input stream.
File
. File
wraps core.stdio.stdin
, and is therefore thread global. Reassigning stdin
to a different File
must be done in a single-threaded or locked context in order to avoid race conditions. stdin
automatically locks the file globally, and will cause all other threads calling read
to wait until the lock is released. // Read stdin, sort lines, write to stdout import std.algorithm.mutation : copy; import std.algorithm.sorting : sort; import std.array : array; import std.typecons : Yes; void main() { stdin // read from stdin .byLineCopy(Yes.keepTerminator) // copying each line .array() // convert to array of lines .sort() // sort the lines .copy( // copy output of .sort to an OutputRange stdout.lockingTextWriter()); // the OutputRange }
The standard output stream.
File
. File
wraps core.stdio.stdout
, and is therefore thread global. Reassigning stdout
to a different File
must be done in a single-threaded or locked context in order to avoid race conditions. stdout
automatically locks the file globally, and will cause all other threads calling write
to wait until the lock is released. void main() { stdout.writeln("Write a message to stdout."); }
void main() { import std.algorithm.iteration : filter, map, sum; import std.format : format; import std.range : iota, tee; int len; const r = 6.iota .filter!(a => a % 2) // 1 3 5 .map!(a => a * 2) // 2 6 10 .tee!(_ => stdout.writefln("len: %d", len++)) .sum; writeln(r); // 18 }
void main() { import std.algorithm.mutation : copy; import std.algorithm.iteration : map; import std.format : format; import std.range : iota; 10.iota .map!(e => "N: %d".format(e)) .copy(stdout.lockingTextWriter()); // the OutputRange }
The standard error stream.
File
. File
wraps core.stdio.stderr
, and is therefore thread global. Reassigning stderr
to a different File
must be done in a single-threaded or locked context in order to avoid race conditions. stderr
automatically locks the file globally, and will cause all other threads calling write
to wait until the lock is released. void main() { stderr.writeln("Write a message to stderr."); }
Experimental network access via the File interface
Opens a TCP connection to the given host and port, then returns a File struct with read and write access through the same interface as any other file (meaning writef and the byLine ranges work!).
© 1999–2018 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/std_stdio.html