std.stdio
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.
- Source
- std/stdio.d
- License:
- Boost License 1.0.
- Authors:
- Walter Bright, Andrei Alexandrescu, Alex Rønne Petersen
- alias KeepTerminator = std.typecons.Flag!"keepTerminator".Flag;
-
If flag
KeepTerminatoris set toKeepTerminator.yes, then the delimiter is included in the strings returned. - struct File;
-
Encapsulates a
FILE*. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulatingFILE*values directly is unsafe and error-prone in many ways. TheFiletype 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 lastFilevariable bound to a givenFILE*goes out of scope, the underlyingFILE*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! % _
- @safe this(string name, scope const(char)[] stdioOpenmode = "rb");
this(R1, R2)(R1 name)
Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1));
this(R1, R2)(R1 name, R2 mode)
Constraints: if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) && isInputRange!R2 && isSomeChar!(ElementEncodingType!R2)); -
Constructor taking the name of the file to open and the open mode.
Copying one
Fileobject to another results in the twoFileobjects referring to the same underlying file.
The destructor automatically closes the file as soon as noFileobject refers to it anymore.- Parameters:
string namerange or string representing the file name const(char)[] stdioOpenmoderange or string represting the open mode (with the same semantics as in the C standard library fopen function)
- Throws:
-
ErrnoExceptionif the file could not be opened.
- ref @safe File opAssign(File rhs) return;
-
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.
- @trusted void open(string name, scope const(char)[] stdioOpenmode = "rb");
-
Detaches from the current file (throwing on failure), and then attempts to open file
namewith modestdioOpenmode. The mode has the same semantics as in the C standard library fopen function.- Throws:
-
ErrnoExceptionin case of error.
- @trusted void reopen(string name, scope const(char)[] stdioOpenmode = "rb");
-
Reuses the
Fileobject to either open a different file, or change the file mode. Ifnameisnull, the mode of the currently open file is changed; otherwise, a new file is opened, reusing the CFILE*. The function has the same semantics as in the C standard library freopen function.- Note
- Calling
reopenwith anullnameis not implemented in all C runtimes.
- Throws:
-
ErrnoExceptionin case of error.
- @safe void popen(string command, scope const(char)[] stdioOpenmode = "r");
-
Detaches from the current file (throwing on failure), and then runs a command by calling the C standard library function popen.
- Throws:
-
ErrnoExceptionin case of error.
- @safe void fdopen(int fd, scope const(char)[] stdioOpenmode = "rb");
-
First calls
detach(throwing on failure), then attempts to associate the given file descriptor with theFile, and sets the file's name tonull.The mode must be compatible with the mode of the file descriptor.
- Throws:
-
ErrnoExceptionin case of error.
- Parameters:
int fdFile descriptor to associate with this File.const(char)[] stdioOpenmodeMode to associate with this File. The mode has the same semantics semantics as in the C standard library fdopen function, and must be compatible with fd.
- void windowsHandleOpen(HANDLE handle, scope const(char)[] stdioOpenmode);
-
First calls
detach(throwing on failure), and then attempts to associate the given WindowsHANDLEwith theFile. The mode must be compatible with the access attributes of the handle. Windows only.- Throws:
-
ErrnoExceptionin case of error.
- const pure nothrow @property @safe bool isOpen();
-
Returns
trueif the file is opened. - const pure @property @trusted bool eof();
-
Returns
trueif the file is at end (see feof).- Throws:
-
Exceptionif the file is not opened.
- const pure nothrow @property @safe string name();
-
Returns the name last used to initialize this
File, if any.Some functions that create or initialize the
Fileset the name field tonull. Examples includetmpfile,wrapFile, andfdopen. See the documentation of those functions for details.- Returns:
- The name last used to initialize this this file, or
nullotherwise.
- const pure nothrow @property @trusted bool error();
-
If the file is not opened, returns
true. Otherwise, returns ferror for the file handle. - @trusted void detach();
-
Detaches from the underlying file. If the sole owner, calls
close.- Throws:
-
ErrnoExceptionon failure if closing the file.
- @trusted void 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
Fileobject is empty. This is different fromdetachin that it always closes the file; consequently, all otherFileobjects referring to the same handle will see a closed file henceforth.- Throws:
-
ErrnoExceptionon error.
- pure nothrow @safe void clearerr();
-
If the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.
- @trusted void flush();
-
Flushes the C
FILEbuffers.Calls fflush for the file handle.
- Throws:
-
Exceptionif the file is not opened or if the call tofflushfails.
- @trusted void sync();
-
Forces any data buffered by the OS to be written to disk. Call
flushbefore calling this function to flush the CFILEbuffers first.This function calls
FlushFileBufferson Windows andfsyncon POSIX for the file handle.- Throws:
-
Exceptionif the file is not opened or if the OS call fails.
- 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.
- Returns:
- The slice of
buffercontaining the data that was actually read. This will be shorter thanbufferif EOF was reached before the buffer could be filled.
- Throws:
-
Exceptionifbufferis empty.ErrnoExceptionif the file is not opened or the call tofreadfails.rawReadalways reads in binary mode on Windows.
- Examples:
-
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"
- 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 not be written in its entirety.
rawWritealways writes in binary mode on Windows.- Throws:
-
ErrnoExceptionif the file is not opened or if the call tofwritefails.
- Examples:
-
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"
- @trusted void seek(long offset, int origin = SEEK_SET);
-
Calls fseek for the file handle to move its position indicator.
- Parameters:
long offsetBinary files: Number of bytes to offset from origin.
Text files: Either zero, or a value returned bytell.int originBinary files: Position used as reference for the offset, must be one of SEEK_SET, SEEK_CUR or SEEK_END.
Text files: Shall necessarily be SEEK_SET.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionif the call tofseekfails.
- const @property @trusted ulong tell();
-
Calls ftell for the managed file handle.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionif the call toftellfails.
- Examples:
-
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
- @safe void rewind();
-
Calls rewind for the file handle.
- Throws:
-
Exceptionif the file is not opened.
- @trusted void setvbuf(size_t size, int mode = _IOFBF);
-
Calls setvbuf for the file handle.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionif the call tosetvbuffails.
- @trusted void setvbuf(void[] buf, int mode = _IOFBF);
-
Calls setvbuf for the file handle.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionif the call tosetvbuffails.
- 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
startandlengthare zero, the entire file is locked.Locks created using
lockandtryLockhave the following properties:- All locks are automatically released when the process terminates.
- Locks are not inherited by child processes.
- Closing a file will release all locks associated with the file. On POSIX, even locks acquired via a different
Filewill be released as well. - Not all NFS implementations correctly implement file locking.
- bool tryLock(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0);
-
Attempts to lock the specified file segment. If both
startandlengthare zero, the entire file is locked.- Returns:
-
trueif the lock was successful, andfalseif the specified file segment was already locked.
- 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.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionon an error writing to the file.
- void writeln(S...)(S args);
-
Writes its arguments in text format to the file, followed by a newline.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionon an error writing to the file.
- void writef(alias fmt, A...)(A args)
Constraints: if (isSomeString!(typeof(fmt)));
void writef(Char, A...)(in Char[] fmt, A args); -
Writes its arguments in text format to the file, according to the format string fmt.
- Parameters:
Char[] fmtThe format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. A argsItems to write.
- Throws:
-
Exceptionif the file is not opened.ErrnoExceptionon an error writing to the file.
- void writefln(alias fmt, A...)(A args)
Constraints: if (isSomeString!(typeof(fmt)));
void writefln(Char, A...)(in Char[] fmt, A args); -
Equivalent to
file.writef(fmt, args, '\n'). - S readln(S = string)(dchar terminator = '\x0a')
Constraints: if (isSomeString!S); -
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.- Parameters:
S Template parameter; the type of the allocated buffer, and the type returned. Defaults to string.dchar terminatorLine terminator (by default, '\n').
- Note
- String terminators are not supported due to ambiguity with readln(buf) below.
- Returns:
- The line that was read, including the line terminator character.
- Throws:
-
StdioExceptionon I/O error, orUnicodeExceptionon Unicode conversion error.
- Example
// Reads `stdin` and writes it to `stdout`. import std.stdio; void main() { string line; while ((line = stdin.readln()) !is null) write(line); } - size_t readln(C)(ref C[] buf, dchar terminator = '\x0a')
Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));
size_t readln(C, R)(ref C[] buf, R terminator)
Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); -
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.- Parameters:
C[] bufBuffer used to store the resulting line data. buf is enlarged if necessary, then set to the slice exactly containing the line. dchar terminatorLine terminator (by default, '\n'). Usestd.ascii.newlinefor portability (unless the file was opened in text mode).
- Returns:
- 0 for end of file, otherwise number of characters read. The return value will always be equal to
buf.length.
- Throws:
-
StdioExceptionon I/O error, orUnicodeExceptionon Unicode conversion error.
- Example
// Read lines from `stdin` into a string // Ignore lines starting with '#' // Write the string to `stdout` import std.stdio; 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 becausestdin.readln(buf)reuses (if possible) memory allocated forbuf, whereasline = stdin.readln()makes a new memory allocation for every line. For even better performance you can helpreadlnby passing in a large buffer to avoid memory reallocations. This can be done by reusing the largest buffer returned byreadln:- Example
// Read lines from `stdin` and count words import std.array, std.stdio; 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 whatbyLinedoes internally, so its usage is recommended if you want to process a complete file. - uint readf(alias format, Data...)(auto ref Data data)
Constraints: if (isSomeString!(typeof(format)));
uint readf(Data...)(scope const(char)[] format, auto ref Data data); -
Reads formatted data from the file using
std.format.formattedRead.- Parameters:
const(char)[] formatThe format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. Data dataItems to be read.
- Example
// 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
- Examples:
-
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);
- static @safe File tmpfile();
-
Returns a temporary file by calling tmpfile. Note that the created file has no
name. - static @safe File wrapFile(FILE* f);
-
Unsafe function that wraps an existing
FILE*. The resultingFilenever takes the initiative in closing the file. Note that the created file has noname - pure @safe FILE* getFP();
-
Returns the
FILE*corresponding to this object. - const @property @trusted int fileno();
-
Returns the file number corresponding to this object.
- @property HANDLE windowsHandle();
-
Returns the underlying operating system
HANDLE(Windows only). - auto byLine(Terminator = char, Char = char)(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a')
Constraints: if (isScalarType!Terminator);
auto byLine(Terminator, Char = char)(KeepTerminator keepTerminator, Terminator terminator)
Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); -
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 throwStdioExceptionon I/O error.- Note
- Each
frontwill not persist afterpopFrontis called, so the caller must copy its contents (e.g. by callingto!string) when retention is needed. If the caller needs to retain a copy of every line, use thebyLineCopyfunction instead.
- Parameters:
Char Character type for each line, defaulting to char.KeepTerminator keepTerminatorUse Yes.keepTerminatorto include the terminator at the end of each line.Terminator terminatorLine separator ( '\n'by default). Usestd.ascii.newlinefor portability (unless the file was opened in text mode).
- Example
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); }- Example
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 byfrontafter the correspondingpopFrontcall is made (because the contents may well have changed). - auto byLineCopy(Terminator = char, Char = immutable(char))(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\x0a')
Constraints: if (isScalarType!Terminator);
auto byLineCopy(Terminator, Char = immutable(char))(KeepTerminator keepTerminator, Terminator terminator)
Constraints: if (is(immutable(ElementEncodingType!Terminator) == immutable(Char))); -
Returns an input range set up to read from the file handle one line at a time. Each line will be newly allocated.
frontwill cache its value to allow repeated calls without unnecessary allocations.- Note
- Due to caching byLineCopy can be more memory-efficient than
File.byLine.map!idup.
Char[]. Range primitives may throwStdioExceptionon I/O error.- Parameters:
Char Character type for each line, defaulting to immutable char.KeepTerminator keepTerminatorUse Yes.keepTerminatorto include the terminator at the end of each line.Terminator terminatorLine separator ( '\n'by default). Usestd.ascii.newlinefor portability (unless the file was opened in text mode).
- Example
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); }- See Also:
std.file.readText
- auto byRecord(Fields...)(string format);
-
Creates an input range set up to parse one line at a time from the file into a tuple.
Range primitives may throw
StdioExceptionon I/O error.- Parameters:
string formattuple record format
- Returns:
- The input range set up to parse one line at a time into a record tuple.
- Examples:
-
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++] }
- auto byChunk(size_t chunkSize);
auto byChunk(ubyte[] buffer); -
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 throwStdioExceptionon I/O error.- Example
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,byChunkaccepts a user-provided buffer that it uses directly.- Example
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 meansfrontwill not persist afterpopFrontis called, so if retention is needed, the caller must copy its contents (e.g. by callingbuffer.dup). In the example above,buffer.lengthis 4096 for all iterations, except for the last one, in which casebuffer.lengthmay be less than 4096 (but always greater than zero). With the mentioned limitations,byChunkworks with any algorithm compatible with input ranges.- Example
// Efficient file copy, 1MB at a time. import std.algorithm, std.stdio; void main() { stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter()); }std.algorithm.iteration.joinercan be used to join chunks together into a single range lazily.- Example
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)); }- Returns:
- A call to
byChunkreturns a range initialized with theFileobject and the appropriate buffer.
- Throws:
- If the user-provided size is zero or the user-provided buffer is empty, throws an
Exception. In case of an I/O error throwsStdioException.
- @safe auto lockingTextWriter();
-
Output range which locks the file when created, and unlocks the file when it goes out of scope.
- Returns:
- An output range which accepts string types,
ubyte[], individual character types, and individualubytes.
- Note
- Writing either arrays of
chars orubytes 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.
- Throws:
-
std.utf.UTFExceptionif the data given is acharrange and it contains malformed UTF data.
- See Also:
-
byChunkfor an example.
- auto lockingBinaryWriter();
-
Returns an output range that locks the file and allows fast writing to it.
- Example
- Produce a grayscale image of the Mandelbrot set in binary Netpbm format to standard output.
import std.algorithm, std.complex, 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 * complex(0, 1) + a[n-1]^^2)(complex(0)) .take(ubyte.max) .countUntil!(z => z.re^^2 + z.im^^2 > 4)) ) ) .copy(stdout.lockingBinaryWriter); } - @property @safe ulong size();
-
Returns 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; void main() { string deleteme = "delete.me"; auto file_handle = File(deleteme, "w"); file_handle.write("abc"); //create temporary file scope(exit) deleteme.remove; //remove temporary file at scope exit assert(file_handle.size() == 3); //check if file size is 3 bytes }
- enum LockType: int;
-
Used to specify the lock type for
File.lockandFile.tryLock.- read
-
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.
- readWrite
-
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.
- enum auto isFileHandle(T);
-
Indicates whether
Tis a file handle, i.e. the type is implicitly convertable toFileor a pointer to acore.stdc.stdio.FILE.- Returns:
-
trueifTis a file handle,falseotherwise.
- Examples:
-
static assert(isFileHandle!(FILE*)); static assert(isFileHandle!(File));
- void write(T...)(T args)
Constraints: if (!is(T[0] : File)); -
Writes its arguments in text format to standard output (without a trailing newline).
- Parameters:
T argsthe items to write to stdout
- Throws:
- In case of an I/O error, throws an
StdioException.
- Example
- Reads
stdinand writes it tostdoutwith 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"); } } - void writeln(T...)(T args);
-
Equivalent to
write(args, '\n'). Callingwritelnwithout arguments is valid and just prints a newline to the standard output.- Parameters:
T argsthe items to write to stdout
- Throws:
- In case of an I/O error, throws an
StdioException.
- Example
- Reads
stdinand writes it tostdoutwith an argument counter.
import std.stdio; void main() { string line; for (size_t count = 0; (line = readln) !is null; count++) { writeln("Input ", count, ": ", line); } } - void writef(alias fmt, A...)(A args)
Constraints: if (isSomeString!(typeof(fmt)));
void writef(Char, A...)(in Char[] fmt, A args); -
Writes formatted data to standard output (without a trailing newline).
- Parameters:
Char[] fmtThe format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. A argsItems to write.
- Note
- In older versions of Phobos, it used to be possible to write:
writef(stderr, "%s", "message");
to print a message tostderr. This syntax is no longer supported, and has been superceded by:stderr.writef("%s", "message"); - void writefln(alias fmt, A...)(A args)
Constraints: if (isSomeString!(typeof(fmt)));
void writefln(Char, A...)(in Char[] fmt, A args); -
Equivalent to
writef(fmt, args, '\n'). - uint readf(alias format, A...)(auto ref A args)
Constraints: if (isSomeString!(typeof(format)));
uint readf(A...)(scope const(char)[] format, auto ref A args); -
Reads formatted data from
stdinusingstd.format.formattedRead.- Parameters:
const(char)[] formatThe format string. When passed as a compile-time argument, the string will be statically checked against the argument types passed. A argsItems to be read.
- Example
// 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
- S readln(S = string)(dchar terminator = '\x0a')
Constraints: 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)version, which may offer better performance as it can reuse its read buffer.- Returns:
- The line that was read, including the line terminator character.
- Parameters:
S Template parameter; the type of the allocated buffer, and the type returned. Defaults to string.dchar terminatorLine terminator (by default, '\n').
- Note
- String terminators are not supported due to ambiguity with readln(buf) below.
- Throws:
-
StdioExceptionon I/O error, orUnicodeExceptionon Unicode conversion error.
- Example
- Reads
stdinand writes it tostdout.
import std.stdio; void main() { string line; while ((line = readln()) !is null) write(line); } - size_t readln(C)(ref C[] buf, dchar terminator = '\x0a')
Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));
size_t readln(C, R)(ref C[] buf, R terminator)
Constraints: if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))); -
Read line from
stdinand 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.- Returns:
-
size_t0 for end of file, otherwise number of characters read
- Parameters:
C[] bufBuffer used to store the resulting line data. buf is resized as necessary. dchar terminatorLine terminator (by default, '\n'). Usestd.ascii.newlinefor portability (unless the file was opened in text mode).
- Throws:
-
StdioExceptionon I/O error, orUnicodeExceptionon Unicode conversion error.
- Example
- Reads
stdinand writes it tostdout.
import std.stdio; void main() { char[] buf; while (readln(buf)) write(buf); } - nothrow @nogc @trusted FILE* _popen(R1, R2)(R1 name, R2 mode = "r")
Constraints: if ((isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) || isSomeString!R1) && (isInputRange!R2 && isSomeChar!(ElementEncodingType!R2) || isSomeString!R2)); -
Convenience function that forwards to
core.sys.posix.stdio.popenwith appropriately-constructed C-style strings. - struct lines;
-
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 forline, and the behavior oflineschanges accordingly:- If
linehas typestring,wstring, ordstring, a new string of the respective type is 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.
ulongoruint) 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, anStdioExceptionis thrown.- See Also:
byLine
- this(File f, dchar terminator = '\x0a');
-
Constructor.
- Parameters:
File fFile to read lines from. dchar terminatorLine separator ( '\n'by default).
- auto chunks(File f, size_t size);
-
Iterates through a file a chunk at a time by using
foreach.- Example
void main() { foreach (ubyte[] buffer; chunks(stdin, 4096)) { ... use buffer ... } }The content ofbufferis reused across calls. In the example above,buffer.lengthis 4096 for all iterations, except for the last one, in which casebuffer.lengthmay be less than 4096 (but always greater than zero). In case of an I/O error, anStdioExceptionis thrown. - void toFile(T)(T data, string fileName)
Constraints: if (is(typeof(copy(data, stdout.lockingBinaryWriter)))); -
Writes an array or range to a file. Shorthand for
data.copy(File(fileName, "wb").lockingBinaryWriter). Similar tostd.file.write, strings are written as-is, rather than encoded according to theFile's orientation. - class StdioException: object.Exception;
-
Thrown if I/O errors happen.
- uint errno;
-
Operating system error code.
- @trusted this(string message, uint e = core.stdc.errno.errno);
-
Initialize with a message and an error code.
- static void opCall(string msg);
static void opCall(); -
Convenience functions that throw an
StdioException.
- alias stdin = makeGlobal!"core.stdc.stdio.stdin".makeGlobal;
-
The standard input stream.
- Returns:
- stdin as a
File.
- Note
- The returned
Filewrapscore.stdc.stdio.stdin, and is therefore thread global. Reassigningstdinto a differentFilemust be done in a single-threaded or locked context in order to avoid race conditions.
stdinautomatically locks the file globally, and will cause all other threads callingreadto wait until the lock is released.- Examples:
-
// 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 }
- alias stdout = makeGlobal!"core.stdc.stdio.stdout".makeGlobal;
-
The standard output stream.
- Returns:
- stdout as a
File.
- Note
- The returned
Filewrapscore.stdc.stdio.stdout, and is therefore thread global. Reassigningstdoutto a differentFilemust be done in a single-threaded or locked context in order to avoid race conditions.
stdoutautomatically locks the file globally, and will cause all other threads callingwriteto wait until the lock is released.- Examples:
-
void main() { stdout.writeln("Write a message to stdout."); }
- Examples:
-
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 }
- Examples:
-
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 }
- alias stderr = makeGlobal!"core.stdc.stdio.stderr".makeGlobal;
-
The standard error stream.
- Returns:
- stderr as a
File.
- Note
- The returned
Filewrapscore.stdc.stdio.stderr, and is therefore thread global. Reassigningstderrto a differentFilemust be done in a single-threaded or locked context in order to avoid race conditions.
stderrautomatically locks the file globally, and will cause all other threads callingwriteto wait until the lock is released.- Examples:
-
void main() { stderr.writeln("Write a message to stderr."); }
- File openNetwork(string host, ushort port);
-
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!).
- Authors:
- Adam D. Ruppe
- Bugs:
- Only works on Linux
© 1999–2021 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/std_stdio.html