Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.stdio

CategorySymbols
File handles_popen File isFileHandle openNetwork stderr stdin stdout 
Readingchunks lines readf readfln readln 
WritingtoFile write writef writefln writeln 
MiscKeepTerminator LockType StdioException 
Standard I/O functions that extendcore.stdc.stdio.core.stdc.stdioispublically imported when importingstd.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'sstdio.h which unifies the two operating system schemes.
  3. std.stdio, this module, unifies the variousstdio.h implementations intoa high level package for D programs.

Sourcestd/stdio.d

License:
Boost License 1.0.
Authors:
Walter Bright,Andrei Alexandrescu, Alex Rønne Petersen
aliasKeepTerminator = std.typecons.Flag!"keepTerminator".Flag;
If flagKeepTerminator is set toKeepTerminator.yes, then the delimiteris included in the strings returned.
structFile;
Encapsulates aFILE*. Generally D does not attempt to providethin wrappers over equivalent functions in the C standard library, butmanipulatingFILE* values directly is unsafe and error-prone inmany ways. TheFile type ensures safe manipulation, automaticfile closing, and a lot of convenience.
The underlyingFILE* handle is maintained in a reference-countedmanner, such that as soon as the lastFile variable bound to agivenFILE* goes out of scope, the underlyingFILE* isautomatically closed.

Example

// test.dimport 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.txtHello, Jimmy!% _

@safe this(stringname, scope const(char)[]stdioOpenmode = "rb");

this(R1, R2)(R1name)
if (isSomeFiniteCharInputRange!R1);

this(R1, R2)(R1name, R2mode)
if (isSomeFiniteCharInputRange!R1 && isSomeFiniteCharInputRange!R2);
Constructor taking the name of the file to open and the open mode.
Copying oneFile object 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:
stringnamerange or string representing the file name
const(char)[]stdioOpenmoderange or string represting the open mode (with the same semantics as in the C standard libraryfopen function)
Throws:
ErrnoException if the file could not be opened.
ref @safe FileopAssign(Filerhs) return;
Assigns a file to another. The target of the assignment gets detachedfrom whatever file it was attached to, and attaches itself to the newfile.
@trusted voidopen(stringname, scope const(char)[]stdioOpenmode = "rb");
Detaches from the current file (throwing on failure), and then attempts toopen filename with modestdioOpenmode. The mode has thesame semantics as in the C standard libraryfopen function.
Throws:
ErrnoException in case of error.
@trusted voidreopen(stringname, scope const(char)[]stdioOpenmode = "rb");
Reuses theFile object to either open a different file, or changethe file mode. Ifname isnull, the mode of the currently openfile is changed; otherwise, a new file is opened, reusing the CFILE*. The function has the same semantics as in the C standardlibraryfreopen function.

NoteCallingreopen with anullname is not implementedin all C runtimes.

Throws:
ErrnoException in case of error.
@safe voidpopen(stringcommand, scope const(char)[]stdioOpenmode = "r");
Detaches from the current file (throwing on failure), and then runs a commandby calling the C standard library functionpopen.
Throws:
ErrnoException in case of error.
@safe voidfdopen(intfd, scope const(char)[]stdioOpenmode = "rb");
First callsdetach (throwing on failure), then attempts toassociate 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:
ErrnoException in case of error.
Parameters:
intfdFile descriptor to associate with thisFile.
const(char)[]stdioOpenmodeMode to associate with this File. The mode has the same semantics as in the POSIX library functionfdopen and must be compatible withfd.
voidwindowsHandleOpen(HANDLEhandle, scope const(char)[]stdioOpenmode);
First callsdetach (throwing on failure), and then attempts toassociate the given WindowsHANDLE with theFile. The mode mustbe compatible with the access attributes of the handle. Windows only.
Throws:
ErrnoException in case of error.
pure nothrow @property @safe boolisOpen() const;
Returnstrue if the file is opened.
pure @property @trusted booleof() const;
Returnstrue if the file is at end (seefeof).
Throws:
Exception if the file is not opened.
pure nothrow @property @safe stringname() const return;
Returns the name last used to initialize thisFile, if any.
Some functions that create or initialize theFile set 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, ornull otherwise.
pure nothrow @property @trusted boolerror() const;
If the file is closed or not yet opened, returnstrue. Otherwise, returnsferror for the file handle.
@trusted voiddetach();
Detaches from the underlying file. If the sole owner, callsclose.
Throws:
ErrnoException on failure if closing the file.
@trusted voidclose();
If the file was closed or not yet opened, succeeds vacuously. Otherwisecloses the file (by callingfclose),throwing on error. Even if an exception is thrown, afterwards theFile object is empty. This is different fromdetach in that italways closes the file; consequently, all otherFile objectsreferring to the same handle will see a closed file henceforth.
Throws:
ErrnoException on error.
pure nothrow @safe voidclearerr();
If the file is closed or not yet opened, succeeds vacuously. Otherwise, returnsclearerr for the file handle.
@trusted voidflush();
Flushes the CFILE buffers.
Callsfflush for the file handle.
Throws:
Exception if the file is not opened or if the call tofflush fails.
@trusted voidsync();
Forces any data buffered by the OS to be written to disk.Callflush before calling this function to flush the CFILE buffers first.
This function callsFlushFileBuffers on Windows,F_FULLFSYNC fcntl on Darwin andfsync on POSIX for the file handle.
Throws:
Exception if the file is not opened or if the OS call fails.
T[]rawRead(T)(T[]buffer);
Callsfread for thefile handle. The number of items to read and the size ofeach item is inferred from the size and type of the input array, respectively.
Returns:
The slice ofbuffer containing the data that was actually read.This will be shorter thanbuffer if EOF was reached before the buffercould be filled. If the buffer is empty, it will be returned.
Throws:
ErrnoException if the file is not opened or the call tofread fails.
rawRead always reads in binary mode on Windows.
Examples:
staticimport 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(newchar[5]);f.close();writeln(buf);// "\r\n\n\r\n"
voidrawWrite(T)(in T[]buffer);
Callsfwrite for the filehandle. The number of items to write and the size of eachitem is inferred from the size and type of the input array, respectively. Anerror is thrown if the buffer could not be written in its entirety.
rawWrite always writes in binary mode on Windows.
Throws:
ErrnoException if the file is not opened or if the call tofwrite fails.
Examples:
staticimport 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 voidseek(longoffset, intorigin = SEEK_SET);
Callsfseekfor the file handle to move its position indicator.
Parameters:
longoffsetBinary files: Number of bytes to offset from origin.
Text files: Either zero, or a value returned bytell.
intoriginBinary files: Position used as reference for the offset, must be one ofSEEK_SET,SEEK_CUR orSEEK_END.
Text files: Shall necessarily beSEEK_SET.
Throws:
Exception if the file is not opened.ErrnoException if the call tofseek fails.
@property @trusted ulongtell() const;
Callsftellfor the managed file handle, which returns the current value ofthe position indicator of the file handle.
Throws:
Exception if the file is not opened.ErrnoException if the call toftell fails.
Examples:
import std.conv : text;staticimport std.file;auto testFile = std.file.deleteme();std.file.write(testFile,"abcdefghijklmnopqrstuvwqxyz");scope(exit) { std.file.remove(testFile); }auto f = File(testFile);auto a =newubyte[4];f.rawRead(a);writeln(f.tell);// 4
@safe voidrewind();
Callsrewind for the file handle.
Throws:
Exception if the file is not opened.
@trusted voidsetvbuf(size_tsize, intmode = _IOFBF);
Callssetvbuf for the file handle.
Throws:
Exception if the file is not opened.ErrnoException if the call tosetvbuf fails.
@trusted voidsetvbuf(void[]buf, intmode = _IOFBF);
Callssetvbuf for the file handle.
Throws:
Exception if the file is not opened.ErrnoException if the call tosetvbuf fails.
voidlock(LockTypelockType = LockType.readWrite, ulongstart = 0, ulonglength = 0);
Locks the specified file segment. If the file segment is already lockedby another process, waits until the existing lock is released.If bothstart andlength are zero, the entire file is locked.
Locks created usinglock andtryLock have 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 differentFile will be released as well.
  • Not all NFS implementations correctly implement file locking.
booltryLock(LockTypelockType = LockType.readWrite, ulongstart = 0, ulonglength = 0);
Attempts to lock the specified file segment.If bothstart andlength are zero, the entire file is locked.
Returns:
true if the lock was successful, andfalse if thespecified file segment was already locked.
voidunlock(ulongstart = 0, ulonglength = 0);
Removes the lock over the specified file segment.
voidwrite(S...)(Sargs);
Writes its arguments in text format to the file.
Throws:
Exception if the file is not opened.ErrnoException on an error writing to the file.
voidwriteln(S...)(Sargs);
Writes its arguments in text format to the file, followed by a newline.
Throws:
Exception if the file is not opened.ErrnoException on an error writing to the file.
voidwritef(alias fmt, A...)(Aargs)
if (isSomeString!(typeof(fmt)));

voidwritef(Char, A...)(in Char[]fmt, Aargs);
Writes its arguments in text format to the file, according to theformat string fmt.
Parameters:
Char[]fmtTheformat string.When passed as a compile-time argument, the string will be statically checkedagainst the argument types passed.
AargsItems to write.
Throws:
Exception if the file is not opened.ErrnoException on an error writing to the file.
voidwritefln(alias fmt, A...)(Aargs)
if (isSomeString!(typeof(fmt)));

voidwritefln(Char, A...)(in Char[]fmt, Aargs);
Equivalent tofile.writef(fmt,args, '\n').
@safe Sreadln(S = string)(dcharterminator = '\n')
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 notretaining a reference to the read data, consider theFile.readln(buf) version, which may offerbetter performance as it can reuse its read buffer.
Parameters:
STemplate parameter; the type of the allocated buffer, and the type returned. Defaults tostring.
dcharterminatorLine terminator (by default,'\n').

NoteString terminators are not supported due to ambiguity with readln(buf) below.

Returns:
The line that was read, including the line terminator character.
Throws:
StdioException on I/O error, orUnicodeException on Unicode conversion error.

Example

// Reads `stdin` and writes it to `stdout`.import std.stdio;void main(){    string line;while ((line = stdin.readln()) !isnull)        write(line);}

@safe size_treadln(C)(ref C[]buf, dcharterminator = '\n')
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));

@safe size_treadln(C, R)(ref C[]buf, Rterminator)
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 tobuf[], includingterminating character.
This can be faster thanline = File.readln() because you can reusethe buffer for each call. Note that reusing the buffer means that youmust copy the previous contents if you wish to retain them.
Parameters:
C[]bufBuffer used to store the resulting line data. buf isenlarged if necessary, then set to the slice exactly containing the line.
dcharterminatorLine terminator (by default,'\n'). Usestd.ascii.newline for portability (unless the file was opened intext mode).
Returns:
0 for end of file, otherwise number of characters read.The return value will always be equal tobuf.length.
Throws:
StdioException on I/O error, orUnicodeException on Unicodeconversion 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 examplebecausestdin.readln(buf) reuses (if possible) memory allocatedforbuf, whereasline = stdin.readln() makes a new memory allocationfor every line.
For even better performance you can helpreadln by passing in alarge buffer to avoid memory reallocations. This can be done by reusing thelargest buffer returned byreadln:

Example

// Read lines from `stdin` and count wordsimport 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 whatbyLine does internally, so its usageis recommended if you want to process a complete file.

uintreadf(alias format, Data...)(auto ref Datadata)
if (isSomeString!(typeof(format)));

uintreadf(Data...)(scope const(char)[]format, auto ref Datadata);
Reads formatted data from the file usingstd.format.formattedRead.
Parameters:
const(char)[]formatTheformat string. When passed as a compile-time argument, the string will be statically checked against the argument types passed.
DatadataItems to be read.
Returns:
Same asformattedRead: The number of variables filled. If the input ranger ends early, this number will be less than the number of variables provided.

Example

// test.dvoid 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.d234

Examples:
staticimport 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);
uintreadfln(alias format, Data...)(auto ref Datadata)
if (isSomeString!(typeof(format)));

uintreadfln(Data...)(scope const(char)[]format, auto ref Datadata);
Reads a line from the file and parses it usingstd.format.read.formattedRead.
Parameters:
const(char)[]formatTheformat string. When passed as a compile-time argument, the string will be statically checked against the argument types passed.
DatadataItems to be read.
Returns:
Same asformattedRead: the number of variables filled. If the input ends early, this number will be less that the number of variables provided.

Example

// sum_rows.dvoid main(){import std.stdio;auto f = File("input");int a, b, c;while (f.readfln("%d %d %d", a, b, c) == 3)    {        writeln(a + b + c);    }}
% cat << EOF > input1 2 34 5 67 8 9EOF% rdmd sum_rows.d61524

static @safe Filetmpfile();
Returns a temporary file by callingtmpfile. Note that the created file has noname.
static @safe FilewrapFile(FILE*f);
Unsafe function that wraps an existingFILE*. The resultingFile never takes the initiative in closing the file.Note that the created file has noname
pure @safe FILE*getFP();
Returns theFILE* corresponding to this object.
@property @trusted fileno_tfileno() const;
Returns the file number corresponding to this object.
@property HANDLEwindowsHandle();
Returns the underlying operating systemHANDLE (Windows only).
autobyLine(Terminator = char, Char = char)(KeepTerminatorkeepTerminator = No.keepTerminator, Terminatorterminator = '\n')
if (isScalarType!Terminator);

autobyLine(Terminator, Char = char)(KeepTerminatorkeepTerminator, Terminatorterminator)
if (is(immutable(ElementEncodingType!Terminator) == immutable(Char)));
Returns aninput rangeset up to read from the file handle one line at a time.
The element type for the range will beChar[]. Range primitivesmay throwStdioException on I/O error.

NoteEachfront will not persist afterpopFront is called, so the caller must copy its contents (e.g. bycallingto!string) when retention is needed. If the caller needsto retain a copy of every line, use thebyLineCopy functioninstead.

Parameters:
CharCharacter type for each line, defaulting tochar.
KeepTerminatorkeepTerminatorUseYes.keepTerminator to include theterminator at the end of each line.
TerminatorterminatorLine separator ('\n' by default). Usestd.ascii.newline for portability (unless the file was opened intext 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 readingconst 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 readingauto range = file.byLine();// Print first three linesforeach (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 byfront after the correspondingpopFront call is made (becausethe contents may well have changed).
Windows specific Example:
import std.stdio;
version (Windows)void main(){
foreach (line; File("file.txt").byLine(No.keepTerminator, "\r\n")){writeln("|"~line~"|");if (line == "HelloWorld") writeln("^This Line is here.");}
}

autobyLineCopy(Terminator = char, Char = immutable(char))(KeepTerminatorkeepTerminator = No.keepTerminator, Terminatorterminator = '\n')
if (isScalarType!Terminator);

autobyLineCopy(Terminator, Char = immutable(char))(KeepTerminatorkeepTerminator, Terminatorterminator)
if (is(immutable(ElementEncodingType!Terminator) == immutable(Char)));
Returns aninput rangeset up to read from the file handle one lineat a time. Each line will be newly allocated.front will cacheits value to allow repeated calls without unnecessary allocations.

NoteDue to caching byLineCopy can be more memory-efficient thanFile.byLine.map!idup.

The element type for the range will beChar[]. Rangeprimitives may throwStdioException on I/O error.

Parameters:
CharCharacter type for each line, defaulting toimmutable char.
KeepTerminatorkeepTerminatorUseYes.keepTerminator to include theterminator at the end of each line.
TerminatorterminatorLine separator ('\n' by default). Usestd.ascii.newline for portability (unless the file was opened intext 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 themforeach (line; sortedLines)        writeln(line);}

autobyRecord(Fields...)(stringformat);
Creates aninput range set up to parse one line at a time from the file into a tuple.
Range primitives may throwStdioException on I/O error.
Parameters:
stringformattuple recordformat
Returns:
The input range set up to parse one line at a time into a record tuple.
See Also:
It is similar tobyLine and usesformat under the hood.
Examples:
staticimport std.file;import std.typecons : tuple;// prepare test fileauto 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++]}
autobyChunk(size_tchunkSize);

autobyChunk(ubyte[]buffer);
Returns aninput rangeset up to read from the file handle a chunk at a time.
The element type for the range will beubyte[]. Range primitivesmay throwStdioException on I/O error.

Example

void main(){// Read standard input 4KB at a timeforeach (ubyte[]buffer; stdin.byChunk(4096))    {        ... usebuffer ...    }}
The parameter may be a number (as shown in the example above) dictating thesize of each chunk. Alternatively,byChunk accepts auser-provided buffer that it uses directly.

Example

void main(){// Read standard input 4KB at a timeforeach (ubyte[]buffer; stdin.byChunk(newubyte[4096]))    {        ... usebuffer ...    }}
In either case, the content of the buffer is reused across calls. That meansfront will not persist afterpopFront is called, so if retention isneeded, the caller must copy its contents (e.g. by callingbuffer.dup).
In the example above,buffer.length is 4096 for all iterations, exceptfor the last one, in which casebuffer.length may be less than 4096 (butalways greater than zero).
With the mentioned limitations,byChunk works with any algorithmcompatible 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.joiner can be used to join chunks together intoa single range lazily.

Example

import std.algorithm, std.stdio;void main(){//Range of rangesstaticassert(is(typeof(stdin.byChunk(4096).front) ==ubyte[]));//Range of elementsstaticassert(is(typeof(stdin.byChunk(4096).joiner.front) ==ubyte));}

Returns:
A call tobyChunk returns a range initialized with theFileobject and the appropriate buffer.
Throws:
If the user-provided size is zero or the user-provided bufferis empty, throws anException. In case of an I/O error throwsStdioException.
@safe autolockingTextWriter();
Output range which locks the file when created, and unlocks the file when it goes out of scope.
Returns:
Anoutput range which accepts string types,ubyte[], individual character types, and individualubytes.

NoteWriting either arrays ofchars 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.UTFException if the data given is achar range and it contains malformed UTF data.
See Also:
byChunk for an example.
autolockingBinaryWriter();
Returns an output range that locks the file and allows fast writing to it.

ExampleProduce a grayscale image of theMandelbrot setin binaryNetpbm 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 ulongsize();
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 filescope(exit) deleteme.remove;//remove temporary file at scope exitassert(file_handle.size() == 3);//check if file size is 3 bytes}

enumLockType: int;
Used to specify the lock type forFile.lock andFile.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 autoisFileHandle(T);
Indicates whetherT is a file handle, i.e. the type is implicitly convertable toFile or a pointer to acore.stdc.stdio.FILE.
Returns:
true ifT is a file handle,false otherwise.
Examples:
staticassert(isFileHandle!(FILE*));staticassert(isFileHandle!(File));
voidwrite(T...)(Targs)
if (!is(T[0] : File));
Writes its arguments in text format to standard output (without a trailing newline).
Parameters:
Targsthe items to write tostdout
Throws:
In case of an I/O error, throws anStdioException.

Example Readsstdin and writes it tostdout with an argument counter.

import std.stdio;void main(){    string line;for (size_t count = 0; (line = readln) !isnull; count++)    {write("Input ", count,": ", line,"\n");    }}

voidwriteln(T...)(Targs);
Equivalent towrite(args, '\n'). Callingwriteln without arguments is valid and just prints a newline to the standard output.
Parameters:
Targsthe items to write tostdout
Throws:
In case of an I/O error, throws anStdioException.

Example Readsstdin and writes it tostdout with an argument counter.

import std.stdio;void main(){    string line;for (size_t count = 0; (line = readln) !isnull; count++)    {writeln("Input ", count,": ", line);    }}

voidwritef(alias fmt, A...)(Aargs)
if (isSomeString!(typeof(fmt)));

voidwritef(Char, A...)(in Char[]fmt, Aargs);
Writes formatted data to standard output (without a trailing newline).
Parameters:
Char[]fmtTheformat string.When passed as a compile-time argument, the string will be statically checkedagainst the argument types passed.
AargsItems 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 hasbeen superceded by:
stderr.writef("%s","message");

voidwritefln(alias fmt, A...)(Aargs)
if (isSomeString!(typeof(fmt)));

voidwritefln(Char, A...)(in Char[]fmt, Aargs);
Equivalent towritef(fmt, args, '\n').
uintreadf(alias format, A...)(auto ref Aargs)
if (isSomeString!(typeof(format)));

uintreadf(A...)(scope const(char)[]format, auto ref Aargs);
Reads formatted data fromstdin usingstd.format.formattedRead.
Parameters:
const(char)[]formatTheformat string. When passed as a compile-time argument, the string will be statically checked against the argument types passed.
AargsItems to be read.
Returns:
Same asformattedRead: The number of variables filled. If the input ranger ends early, this number will be less than the number of variables provided.

Example

// test.dvoid main(){import std.stdio;foreach (_; 0 .. 3)    {int a;readf!" %d"(a);        writeln(++a);    }}
% echo "1 2 3" | rdmd test.d234

Sreadln(S = string)(dcharterminator = '\n')
if (isSomeString!S);
Read line fromstdin.
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 thereadln(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:
STemplate parameter; the type of the allocated buffer, and the type returned. Defaults tostring.
dcharterminatorLine terminator (by default,'\n').

NoteString terminators are not supported due to ambiguity with readln(buf) below.

Throws:
StdioException on I/O error, orUnicodeException on Unicode conversion error.

Example Readsstdin and writes it tostdout.

import std.stdio;void main(){    string line;while ((line =readln()) !isnull)        write(line);}

size_treadln(C)(ref C[]buf, dcharterminator = '\n')
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum));

size_treadln(C, R)(ref C[]buf, Rterminator)
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init)));
Read line fromstdin and write it to buf[], including terminating character.
This can be faster thanline = 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_t 0 for end of file, otherwise number of characters read
Parameters:
C[]bufBuffer used to store the resulting line data. buf is resized as necessary.
dcharterminatorLine terminator (by default,'\n'). Usestd.ascii.newline for portability (unless the file was opened in text mode).
Throws:
StdioException on I/O error, orUnicodeException on Unicode conversion error.

Example Readsstdin and writes it tostdout.

import std.stdio;void main(){char[]buf;while (readln(buf))        write(buf);}

uintreadfln(alias format, Data...)(auto ref Datadata);

uintreadfln(Data...)(scope const(char)[]format, auto ref Datadata);
Reads a line fromstdin and parses it usingstd.format.read.formattedRead.
Parameters:
const(char)[]formatTheformat string. When passed as a compile-time argument, the string will be statically checked against the argument types passed.
DatadataItems to be read.
Returns:
Same asformattedRead: the number of variables filled. If theinput ends early, this number will be less that the number of variablesprovided.

Example

// sum_rows.dvoid main(){import std.stdio;int a, b, c;while (readfln("%d %d %d", a, b, c) == 3)    {        writeln(a + b + c);    }}
% cat << EOF > input1 2 34 5 67 8 9EOF% rdmd sum_rows.d < input61524

nothrow @nogc @trusted FILE*_popen(R1, R2)(R1name, R2mode = "r")
if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) && (isSomeFiniteCharInputRange!R2 || isSomeString!R2));
Convenience function that forwards tocore.sys.posix.stdio.popen with appropriately-constructed C-style strings.
structlines;
Iterates through the lines of a file by usingforeach.

Example

void main(){foreach (string line;lines(stdin))  {    ... use line ...  }}
The line terminator ('\n' by default) is part of the string read (itcould be missing in the last line of the file). Several types aresupported forline, and the behavior oflineschanges accordingly:
  1. Ifline has typestring,wstring, ordstring, a new string of the respective typeis allocated every read.
  2. Ifline has typechar[],wchar[],dchar[], the line's contentwill be reused (overwritten) across reads.
  3. Iflinehas typeimmutable(ubyte)[], the behavior is similar tocase (1), except that no UTF checking is attempted upon input.
  4. Ifline has typeubyte[], the behavior issimilar to case (2), except that no UTF checking is attempted uponinput.
In all cases, a two-symbols versions is also accepted, in which casethe first symbol (of integral type, e.g.ulong oruint) 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, anStdioException is thrown.

See Also:
@safe this(Filef, dcharterminator = '\n');
Constructor.
Parameters:
FilefFile to read lines from.
dcharterminatorLine separator ('\n' by default).
autochunks(Filef, size_tsize);
Iterates through a file a chunk at a time by usingforeach.

Example

void main(){foreach (ubyte[] buffer;chunks(stdin, 4096))    {        ... use buffer ...    }}
The content ofbuffer is reused across calls. In the example above,buffer.length is 4096 for all iterations, except for the last one, in which casebuffer.length may be less than 4096 (but always greater than zero).
In case of an I/O error, anStdioException is thrown.

voidtoFile(T)(Tdata, stringfileName)
if (is(typeof(copy(data, stdout.lockingBinaryWriter))));
Writes an array or range to a file.Shorthand fordata.copy(File(fileName, "wb").lockingBinaryWriter).Similar tostd.file.write, strings are written as-is,rather than encoded according to theFile'sorientation.
classStdioException:object.Exception;
Thrown if I/O errors happen.
uinterrno;
Operating system error code.
@trusted this(stringmessage, uinte = core.stdc.errno.errno);
Initialize with a message and an error code.
static @safe voidopCall(stringmsg);

static @safe voidopCall();
Convenience functions that throw anStdioException.
aliasstdin = makeGlobal!"core.stdc.stdio.stdin".makeGlobal;
The standard input stream.
Returns:
stdin as aFile.

NoteThe returnedFile wrapscore.stdc.stdio.stdin, and is therefore thread global. Reassigningstdin to a differentFile must be done in a single-threaded or locked context in order to avoid race conditions.

All reading fromstdin automatically locks the file globally, and will cause all other threads callingread to wait until the lock is released.

Examples:
// Read stdin, sort lines, write to stdoutimport 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}
aliasstdout = makeGlobal!"core.stdc.stdio.stdout".makeGlobal;
The standard output stream.
Returns:
stdout as aFile.

NoteThe returnedFile wrapscore.stdc.stdio.stdout, and is therefore thread global. Reassigningstdout to a differentFile must be done in a single-threaded or locked context in order to avoid race conditions.

All writing tostdout automatically locks the file globally, and will cause all other threads callingwrite to 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}
aliasstderr = makeGlobal!"core.stdc.stdio.stderr".makeGlobal;
The standard error stream.
Returns:
stderr as aFile.

NoteThe returnedFile wrapscore.stdc.stdio.stderr, and is therefore thread global. Reassigningstderr to a differentFile must be done in a single-threaded or locked context in order to avoid race conditions.

All writing tostderr automatically locks the file globally, and will cause all other threads callingwrite to wait until the lock is released.

Examples:
void main(){stderr.writeln("Write a message to stderr.");}
FileopenNetwork(stringhost, ushortport);
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
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Sat Feb 21 04:08:07 2026

[8]ページ先頭

©2009-2026 Movatter.jp