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:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
  2. C's stdio.h which unifies the two operating system schemes.
  3. std.stdio, this module, unifies the various stdio.h implementations into

    a high level package for D programs.

Source: std/stdio.d

Types 15

aliasKeepTerminator = Flag!"keepTerminator"

If flag KeepTerminator is set to KeepTerminator.yes, then the delimiter is included in the strings returned.

private aliasfileno_t = int
private structByRecordImpl(Fields...)
Fields
File file
char[] line
Tuple!(Fields) current
string format
Methods
bool empty() @propertyRange primitive implementations.
Tuple!(Fields) front() @property refDitto
void popFront()Ditto
Constructors
this(File f, string format)
structFile

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! % __

Fields
private Impl * _p
private string _name
Methods
private void initImpl(FILE * handle, string name, uint refs = 1, bool isPopened = false) @nogc nothrow pure @safe
File 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.
private void resetFile(string name, scope const(char)[] stdioOpenmode, bool isPopened) @trusted
private void closeHandles() @trusted
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) @trusted
bool isOpen() @property const @safe pure nothrowReturns `true` if the file is opened.
bool eof() @property const @trusted pureReturns `true` if the file is at end (see feof).
string 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 detach() @trustedDetaches from the underlying file. If the sole owner, calls `close`.
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 flush() @trustedFlushes the C `FILE` buffers.
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 rewind() @safeCalls rewind for the file handle.
void setvbuf(size_t size, int mode = _IOFBF) @trustedCalls setvbuf for the file handle.
void setvbuf(void[] buf, int mode = _IOFBF) @trustedCalls setvbuf for 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)ditto
void 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)ditto
S 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))) @safeditto
uint 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)ditto
uint 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)ditto
File 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 name
FILE * getFP() @safe pureReturns the `FILE*` corresponding to this object.
fileno_t fileno() @property const @trustedReturns the file number corresponding to this object.
auto 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))ditto
auto 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))ditto
auto 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)Ditto
auto 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;
Constructors
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)ditto
this(R1 name, R2 mode)ditto
Destructors
Nested Templates
Orientation
Impl
ByLineImpl
ByLineCopy
ByLineCopyImpl
byRecord(Fields...)Creates an input range set up to parse one line at a time from the file into a tuple.
ByChunkImpl
LockingTextWriter
BinaryWriterImpl

Used to specify the lock type for File.lock and File.tryLock.

readSpecifies 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 lock...
readWriteSpecifies 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 s...
Fields
private File _f
private char _front
private bool _hasChar
Methods
bool empty() @property
char front() @property
void popFront()
Constructors
Destructors
structlines

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:

  1. If line has type string, wstring, or dstring, a new string of the respective type

    is allocated every read.

  2. If line has type char[], wchar[], dchar[], the line's content will be reused (overwritten) across reads.
  3. If line has type immutable(ubyte)[], the behavior is similar to case (1), except that no UTF checking is attempted upon input.
  4. If line has type ubyte[], 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

Fields
private File f
private dchar terminator
Methods
int opApply(D)(scope D dg)
int opApplyRaw(D)(scope D dg)
Constructors
this(File f, dchar terminator = '\n')Constructor. Params: f = File to read lines from. terminator = Line separator (`'\n'` by default).
private structChunksImpl
Fields
private File f
private size_t size
Methods
int opApply(D)(scope D dg)
Constructors
this(File f, size_t size)
classStdioException : Exception

Thrown if I/O errors happen.

Fields
uint errnoOperating system error code.
Methods
void opCall(string msg) @safeConvenience functions that throw an `StdioException`.
void opCall() @safeditto
Constructors
this(string message, uint e = core.stdc.errno.errno)Initialize with a message and an error code.
enumStdFileHandle : string
stdin = "core.stdc.stdio.stdin"
stdout = "core.stdc.stdio.stdout"
stderr = "core.stdc.stdio.stderr"
aliasstdin = makeGlobal!(StdFileHandle.stdin)

The standard input stream.

Returns

stdin as a File.

Note

The returned File wraps 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.

aliasstdout = makeGlobal!(StdFileHandle.stdout)

The standard output stream.

Returns

stdout as a File.

Note

The returned File wraps 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.

aliasstderr = makeGlobal!(StdFileHandle.stderr)

The standard error stream.

Returns

stderr as a File.

Note

The returned File wraps 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.

private structReadlnAppender
Fields
char[] buf
size_t pos
bool safeAppend
Methods
void initialize(char[] b) @safe
char[] data() @property @trusted
void reserve(size_t n) @trusted
void putchar(char c) @trusted
void putdchar(dchar dc) @trusted
void putonly(const char[] b) @trusted
private structLockedFile
Fields
private _iobuf * fp
Methods
void opAssign(LockedFile) @disable
@trusted fgetc()
@trusted fgetwc()
Constructors
this(FILE * fps)
Destructors

Functions 24

fnint trustedFPUTC(int ch, _iobuf * h) @trusted
fnint trustedFPUTWC(wchar_t ch, _iobuf * h) @trusted
private fnFile trustedStdout() @property @trustedProperty used by writeln/etc. so it can infer @safe since stdout is __gshared
fnvoid write(T...)(T args) if (!is(T[0] : File))Writes its arguments in text format to standard output (without a trailing newline).
fnvoid 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:...
fnvoid writef(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Writes formatted data to standard output (without a trailing newline).
fnvoid writef(Char, A...)(in Char[] fmt, A args)ditto
fnvoid writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt).
fnvoid writefln(Char, A...)(in Char[] fmt, A args)ditto
fnuint 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...
fnuint readf(A...)(scope const(char)[] format, auto ref A args)ditto
fnS 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...
fnsize_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...
fnsize_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)))ditto
fnuint readfln(alias format, Data...)(auto ref Data data)Reads a line from `stdin` and parses it using formattedRead.
fnuint readfln(Data...)(scope const(char)[] format, auto ref Data data)ditto
private fnFILE * _fopen(R1, R2)(R1 name, R2 mode = "r") if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) && (isSomeFiniteCharInputRange!R2 || isSomeString!R2))
private fnauto trustedFwrite(T)(FILE * f, const T[] obj) @trusted
private fnauto trustedFread(T)(FILE * f, T[] obj) if (!imported!"std.traits".hasIndirections!T) @trusted
private fnauto trustedFread(T)(FILE * f, T[] obj) if (imported!"std.traits".hasIndirections!T) @system
fnauto chunks(File f, size_t size)Iterates through a file a chunk at a time by using `foreach`.
fnvoid 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...
fnFile makeGlobal(StdFileHandle _iob)() @property ref
private fnsize_t readlnImpl(FILE * fps, ref char[] buf, dchar terminator, File.Orientation orientation) @safe

Templates 2

tmplbyRecord(Fields...)
Functions
auto byRecord(File f, string format)
tmplisFileHandle(T)

Indicates whether T is a file handle, i.e. the type is implicitly convertable to File or a pointer to a

FILE.

Returns

true if T is a file handle, false otherwise.