std.stdio
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.
There are three layers of I/O:
- The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
- C's
stdio.hwhich unifies the two operating system schemes. std.stdio, this module, unifies the variousstdio.himplementations intoa high level package for D programs.
Source: std/stdio.d
Copyright
Types 15
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.
Example: ---- // test.d import std.stdio;
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! % __
void initImpl(FILE * handle, string name, uint refs = 1, bool isPopened = false) @nogc nothrow pure @safeFile opAssign(File rhs) ref @safe returnAssigns 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.void open(string name, scope const(char)[] stdioOpenmode = "rb") @trustedDetaches 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.void reopen(string name, scope const(char)[] stdioOpenmode = "rb") @trustedReuses 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 ...void fdopen(int fd, scope const(char)[] stdioOpenmode = "rb") @safeFirst calls `detach` (throwing on failure), then attempts to associate the given file descriptor with the `File`, and sets the file's name to `null`.void fdopen(int fd, scope const(char)[] stdioOpenmode, string name) @trustedstring name() @property const @safe pure nothrow returnReturns the name last used to initialize this `File`, if any.bool error() @property const @trusted pure nothrowIf the file is closed or not yet opened, returns `true`. Otherwise, returns ferror for the file handle.void close() @trustedIf the file was closed or not yet opened, succeeds vacuously. Otherwise closes the file (by calling fclose), throwing on error. Even if an exception is thrown, afterwards the File object is empty. ...void clearerr() @safe pure nothrowIf the file is closed or not yet opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.void sync() @trustedForces any data buffered by the OS to be written to disk. Call flush before calling this function to flush the C `FILE` buffers first.T[] rawRead(T)(T[] buffer)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.void rawWrite(T)(in T[] buffer)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 ...void seek(long offset, int origin = SEEK_SET) @trustedCalls fseek for the file handle to move its position indicator.ulong tell() @property const @trustedCalls ftell for the managed file handle, which returns the current value of the position indicator of the file handle.void lock(LockType lockType = LockType.readWrite,
ulong start = 0, ulong length = 0)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.bool tryLock(LockType lockType = LockType.readWrite,
ulong start = 0, ulong length = 0)Attempts to lock the specified file segment. If both `start` and `length` are zero, the entire file is locked. Returns: `true` if the lock was successful, and `false` if the specified file segment ...void unlock(ulong start = 0, ulong length = 0)Removes the lock over the specified file segment.void write(S...)(S args)Writes its arguments in text format to the file.void writeln(S...)(S args)Writes its arguments in text format to the file, followed by a newline.void writef(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Writes its arguments in text format to the file, according to the format string fmt.void writef(Char, A...)(in Char[] fmt, A args)dittovoid writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to `file.writef(fmt, args, '\n')`.void writefln(Char, A...)(in Char[] fmt, A args)dittoS readln(S = string)(dchar terminator = '\n') if (isSomeString!S) @safeRead line from the file handle and return it as a specified type.size_t readln(C)(ref C[] buf, dchar terminator = '\n') if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum)) @safeRead line from the file handle and write it to `buf[]`, including terminating character.size_t readln(C, R)(ref C[] buf, R terminator) if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) &&
isBidirectionalRange!R && is(typeof(terminator.front == dchar.init))) @safedittouint readf(alias format, Data...)(auto ref Data data) if (isSomeString!(typeof(format))) Reads formatted data from the file using formattedRead. Params: format = The format string. When passed as a compile-time argument, the string will be statically checked against the argument t...uint readf(Data...)(scope const(char)[] format, auto ref Data data)dittouint readfln(alias format, Data...)(auto ref Data data) if (isSomeString!(typeof(format)))Reads a line from the file and parses it using formattedRead.uint readfln(Data...)(scope const(char)[] format, auto ref Data data)dittoFile tmpfile() @safeReturns a temporary file by calling tmpfile. Note that the created file has no name.File wrapFile(FILE * f) @safeUnsafe function that wraps an existing `FILE*`. The resulting File never takes the initiative in closing the file. Note that the created file has no nameauto byLine(Terminator = char, Char = char)(KeepTerminator keepTerminator = No.keepTerminator,
Terminator terminator = '\n') if (isScalarType!Terminator)Returns an input range set up to read from the file handle one line at a time.auto byLine(Terminator, Char = char)(KeepTerminator keepTerminator, Terminator terminator) if (is(immutable ElementEncodingType!Terminator == immutable Char))dittoauto byLineCopy(Terminator = char, Char = immutable char)(KeepTerminator keepTerminator = No.keepTerminator,
Terminator terminator = '\n') if (isScalarType!Terminator)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.auto byLineCopy(Terminator, Char = immutable char)(KeepTerminator keepTerminator, Terminator terminator) if (is(immutable ElementEncodingType!Terminator == immutable Char))dittoauto byChunk(size_t chunkSize)Returns an input range set up to read from the file handle a chunk at a time.auto byChunk(ubyte[] buffer)Dittoauto lockingTextWriter() @safeOutput range which locks the file when created, and unlocks the file when it goes out of scope.auto lockingBinaryWriter()Returns an output range that locks the file and allows fast writing to it.ulong size() @property @safeReturns the size of the file in bytes, ulong.max if file is not searchable or throws if the operation fails. Example: --- import std.stdio, std.file;this(FILE * handle, string name, uint refs = 1, bool isPopened = false)this(string name, scope const(char)[] stdioOpenmode = "rb")Constructor taking the name of the file to open and the open mode.this(R1 name)dittothis(R1 name, R2 mode)dittoOrientationImplByLineImplByLineCopyByLineCopyImplbyRecord(Fields...)Creates an input range set up to parse one line at a time from the file into a tuple.ByChunkImplLockingTextWriterBinaryWriterImplUsed to specify the lock type for File.lock and File.tryLock.
Iterates through the lines of a file by using foreach.
Example:
--------- 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:
- If
linehas typestring,wstring, ordstring, a new string of the respective typeis allocated every read.
- If
linehas typechar[],wchar[],dchar[], the line's content will be reused (overwritten) across reads. - If
linehas typeimmutable(ubyte)[], the behavior is similar to case (1), except that no UTF checking is attempted upon input. - If
linehas typeubyte[], the behavior is similar to case (2), except that no UTF checking is attempted upon input.
In all cases, a two-symbols versions is also accepted, in which case the first symbol (of integral type, e.g. ulong or uint) tracks the zero-based number of the current line.
Example: ---- foreach (ulong i, string line; lines(stdin)) { ... use line ... } ----
In case of an I/O error, an StdioException is thrown.
See Also
The standard input stream.
Returns
Note
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.
All reading from stdin automatically locks the file globally, and will cause all other threads calling read to wait until the lock is released.
The standard output stream.
Returns
Note
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.
All writing to stdout automatically locks the file globally, and will cause all other threads calling write to wait until the lock is released.
The standard error stream.
Returns
Note
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.
All writing to stderr automatically locks the file globally, and will cause all other threads calling write to wait until the lock is released.
char[] bufsize_t posbool safeAppendvoid initialize(char[] b) @safebool reserveWithoutAllocating(size_t n)void reserve(size_t n) @trustedvoid putchar(char c) @trustedvoid putdchar(dchar dc) @trustedvoid putonly(const char[] b) @trustedFunctions 24
File trustedStdout() @property @trustedProperty used by writeln/etc. so it can infer @safe since stdout is __gsharedvoid write(T...)(T args) if (!is(T[0] : File))Writes its arguments in text format to standard output (without a trailing newline).void writeln(T...)(T args) Equivalent to `write(args, '\n')`. Calling `writeln` without arguments is valid and just prints a newline to the standard output. Params: args = the items to write to `stdout` Throws:...void writef(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Writes formatted data to standard output (without a trailing newline).uint readf(alias format, A...)(auto ref A args) if (isSomeString!(typeof(format))) Reads formatted data from `stdin` using formattedRead. Params: format = The format string. When passed as a compile-time argument, the string will be statically checked against the argument ty...S readln(S = string)(dchar terminator = '\n') if (isSomeString!S) 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)` v...size_t readln(C)(ref C[] buf, dchar terminator = '\n') if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum)) 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 buff...size_t readln(C, R)(ref C[] buf, R terminator) if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) &&
isBidirectionalRange!R && is(typeof(terminator.front == dchar.init)))dittouint readfln(alias format, Data...)(auto ref Data data)Reads a line from `stdin` and parses it using formattedRead.FILE * _fopen(R1, R2)(R1 name, R2 mode = "r") if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) &&
(isSomeFiniteCharInputRange!R2 || isSomeString!R2))auto trustedFread(T)(FILE * f, T[] obj) if (!imported!"std.traits".hasIndirections!T) @trustedauto trustedFread(T)(FILE * f, T[] obj) if (imported!"std.traits".hasIndirections!T) @systemvoid toFile(T)(T data, string fileName) if (is(typeof(copy(data, stdout.lockingBinaryWriter))))Writes an array or range to a file. Shorthand for data.copy(File(fileName.lockingBinaryWriter)). Similar to write, strings are written as-is, rather than encoded according to the `File`'s en.cppref...size_t readlnImpl(FILE * fps, ref char[] buf, dchar terminator, File.Orientation orientation) @safe