Standard I/O functions that extend std.c. stdio. std.c. stdio is publically imported when importing std. stdio.
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 $(D 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 (with the same semantics as in the C standard library fopen function).
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.
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.
First calls detach (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.
Returns true if the file is opened.
Returns true if the file is at end (see feof).
If the file is not opened, returns false. Otherwise, returns ferror for the file handle.
Detaches from the underlying file. If the sole owner, calls close.
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.
If the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.
Calls fflush for the file handle.
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.
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.
Calls fseek for the file handle.
Calls ftell for the managed file handle.
Calls rewind for the file handle.
Writes its arguments in text format to the file.
Writes its arguments in text format to the file, followed by a newline.
Writes its arguments in text format to the file, according to the format in the first argument.
Writes its arguments in text format to the file, according to the format in the first argument, followed by a newline.
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') |
// Reads $(D stdin) and writes it to $(D 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') |
// Read lines from $(D stdin) into a string // Ignore lines starting with '#' // Write the string to $(D stdout) void main() { string output; char[] buf; while (stdin.readln(buf)) { if (buf[0] == '#') continue; output ~= buf; } write(output); }
Read data from the file according to the specified format specifier using std.format.formattedRead.
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 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.
Char | Character type for each line, defaulting to char. |
KeepTerminator keepTerminator | Use KeepTerminator.yes to include the terminator at the end of each line. |
Terminator terminator | Line separator ('\n' by default). |
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 .reduce!((a, b) => a + b); // 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 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() { foreach (ubyte[] buffer; stdin.byChunk(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).
import std.algorithm, std.stdio; void main() { stdin.byChunk(1024).copy(stdout.lockingTextWriter()); }
Returns an output range that locks the file and allows fast writing to it.
See byChunk for an example.
Get the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.
Indicates whether T is a file handle of some kind.
Scheduled for deprecation in January 2013. Please use isFileHandle instead.
For each argument arg in args, format the argument (as per to!(string)(arg)) and write the resulting string to args[0]. A call without any arguments will fail to compile.
Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.
If the first argument args[0] is a FILE*, use the format specifier in args[1] to control the formatting of args[2..$], and write the resulting string to args[0]. If arg[0] is not a FILE*, the call is equivalent to writef(stdout, args).
writef("Date: %2$s %1$s", "October", 5); // "Date: 5 October"
Equivalent to writef(args, '\n').
Read data from stdin according to the specified format specifier using std.format.formattedRead.
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') |
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.
C[] buf | Buffer used to store the resulting line data. buf is resized as necessary. |
dchar terminator | line terminator (by default, '\n') |
import std.stdio; void main() { char[] buf; while (readln(buf)) write(buf); }
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:
foreach (ulong i, string line; lines(stdin)) { ... use line ... }
Iterates through a file a chunk at a time by using foreach.
void main() { foreach (ubyte[] buffer; chunks(stdin, 4096)) { ... use buffer ... } }
Thrown if I/O errors happen.
The standard input stream.
The standard output stream.
The standard error stream.