std.stdio

View Source
Standard I/O functions that extend std.c.stdio. std.c.stdio is publically imported when importing std.stdio.

Source:
std/stdio.d

License:
Boost License 1.0.

Authors:
Walter Bright, Andrei Alexandrescu

Class Quick Reference
Class NameDescription
Uncategorized
StdioExceptionThrown if I/O errors happen.
Struct Quick Reference
Struct NameDescription
Uncategorized
FileEncapsulates 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.
chunksIterates through a file a chunk at a time by using foreach.
linesIterates through the lines of a file by using foreach.
Function Quick Reference
Function NameDescription
Uncategorized
popenConvenience function that forwards to std.c.stdio.popen with appropriately-constructed C-style strings.
readfFormatted read one line from stdin.
readlnRead line from stream fp.
writeFor each argument arg in args, format the argument (as per to!(string)(arg)) and write the resulting string to args[0]. A call without any arguments will fail to compile.
writefIf the first argument args[0] is a FILE*, use the format specifier in args[1] to control the formatting of args[2..$], and write the resulting string to args[0]. If arg[0] is not a FILE*, the call is equivalent to writef(stdout, args).
writeflnEquivalent to writef(args, '\n').
writelnEquivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.
struct File;
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
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!
% _

Member Quick Reference
Member NameDescription
Uncategorized
ByChunkRange that reads a chunk at a time.
ByLineRange that reads one line at a time.
KeepTerminatorRange that reads one line at a time.
LockingTextWriterRange that locks the file and allows fast writing to it.
byChunkIterates through a file a chunk at a time by using foreach.
byLineConvenience function that returns the LinesReader corresponding to this file.
clearerrIf the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.
closeIf the file was unopened, succeeds vacuously. Otherwise closes the file (by calling fclose), throwing on error. Even if an exception is thrown, afterwards the File object is empty. This is different from detach in that it always closes the file; consequently, all other File objects referring to the same handle will see a closed file henceforth.
detachDetaches from the underlying file. If the sole owner, calls close and throws if that fails.
emptyRange primitive operations.
eofReturns true if the file is at end (see feof). The file must be opened, otherwise an exception is thrown.
errorIf the file is not opened, returns false. Otherwise, returns ferror for the file handle.
filenoReturns the file number corresponding to this object.
flushIf the file is not opened, throws an exception. Otherwise, calls fflush for the file handle and throws on error.
frontRange primitive operations.
getFPReturns the FILE* corresponding to this object.
isOpenReturns true if the file is opened.
lockingTextWriterConvenience function.
nameReturns the name of the file, if any.
opAssignAssigns 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.
openFirst calls detach (throwing on failure), and then attempts to open file name with mode stdioOpenmode. The mode has the same semantics as in the C standard library fopen function. Throws exception in case of error.
popFrontRange primitive operations.
popenFirst calls detach (throwing on failure), and then runs a command by calling the C standard library function popen.
putRange primitive implementations.
rawReadIf the file is not opened, throws an exception. Otherwise, calls fread for the file handle and throws on error.
rawWriteIf the file is not opened, throws an exception. Otherwise, calls fwrite for the file handle and throws on error.
readlnRead line from stream fp and write it to buf[], including terminating character.
rewindIf the file is not opened, throws an exception. Otherwise, calls rewind for the file handle. Throws on error.
seekIf the file is not opened, throws an exception. Otherwise, calls fseek for the file handle. Throws on error.
setvbufIf the file is not opened, throws an exception. Otherwise, calls setvbuf for the file handle.
sizeGet the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.
tellIf the file is not opened, throws an exception. Otherwise, calls ftell for the managed file handle. Throws on error.
tmpfileReturns a temporary file by calling tmpfile.
wrapFileUnsafe function that wraps an existing FILE*. The resulting File never takes the initiative in closing the file.
writeIf the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file.
writefIf the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file, according to the format in the first argument.
writeflnSame as writef, plus adds a newline.
writelnIf the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file, followed by a newline.
this(string name, in const(char[]) stdioOpenmode = "rb");
Constructor taking the name of the file to open and the open mode (with the same semantics as in the C standard library fopen function). Throws an exception if the file could not be opened.

Copying one File object to another results in the two File objects referring to the same underlying file.

The destructor automatically closes the file as soon as no File object refers to it anymore.

void opAssign(File rhs);
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.

void open(string name, in char[] stdioOpenmode = "rb");
First calls detach (throwing on failure), and then attempts to open file name with mode stdioOpenmode. The mode has the same semantics as in the C standard library fopen function. Throws exception in case of error.

void popen(string command, in char[] stdioOpenmode = "r");
First calls detach (throwing on failure), and then runs a command by calling the C standard library function popen.

const @property bool isOpen();
Returns true if the file is opened.

const @property bool eof();
Returns true if the file is at end (see feof). The file must be opened, otherwise an exception is thrown.

const @property string name();
Returns the name of the file, if any.

const @property bool error();
If the file is not opened, returns false. Otherwise, returns ferror for the file handle.

void detach();
Detaches from the underlying file. If the sole owner, calls close and throws if that fails.

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 File object is empty. This is different from detach in that it always closes the file; consequently, all other File objects referring to the same handle will see a closed file henceforth.

void clearerr();
If the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.

void flush();
If the file is not opened, throws an exception. Otherwise, calls fflush for the file handle and throws on error.

T[] rawRead(T)(T[] buffer);
If the file is not opened, throws an exception. Otherwise, calls fread for the file handle and throws on error.

rawRead always read in binary mode on Windows.

void rawWrite(T)(in T[] buffer);
If the file is not opened, throws an exception. Otherwise, calls fwrite for the file handle and throws on error.

rawWrite always write in binary mode on Windows.

void seek(long offset, int origin = SEEK_SET);
If the file is not opened, throws an exception. Otherwise, calls fseek for the file handle. Throws on error.

const @property ulong tell();
If the file is not opened, throws an exception. Otherwise, calls ftell for the managed file handle. Throws on error.

void rewind();
If the file is not opened, throws an exception. Otherwise, calls rewind for the file handle. Throws on error.

void setvbuf(size_t size, int mode = _IOFBF);
If the file is not opened, throws an exception. Otherwise, calls setvbuf for the file handle.

void setvbuf(void[] buf, int mode = _IOFBF);
If the file is not opened, throws an exception. Otherwise, calls setvbuf for the file handle.

void write(S...)(S args);
If the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file.

void writeln(S...)(S args);
If the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file, followed by a newline.

void writef(S...)(S args);
If the file is not opened, throws an exception. Otherwise, writes its arguments in text format to the file, according to the format in the first argument.

void writefln(S...)(S args);
Same as writef, plus adds a newline.

S readln(S = string)(dchar terminator = '\x0a');
size_t readln(C)(ref C[] buf, dchar terminator = '\x0a');
size_t readln(C, R)(ref C[] buf, R terminator);
Read line from stream fp and write it to buf[], including terminating character.

This is often faster than File.readln(dchar) because the buffer is reused each call. Note that reusing the buffer means that the previous contents of it has to be copied if needed.

Parameters:
fp input stream
buf buffer used to store the resulting line data. buf is resized as necessary.

Returns:
0 for end of file, otherwise number of characters read

Throws:
StdioException on error

Example:
// Reads stdin and writes it to stdout.
import std.stdio;

int main()
{
    char[] buf;
    while (stdin.readln(buf))
        write(buf);
    return 0;
}
This method is more efficient than the one in the previous example because stdin.readln(buf) reuses (if possible) memory allocated by buf, whereas buf = stdin.readln() makes a new memory allocation with every line.

static File tmpfile();
Returns a temporary file by calling tmpfile.

static File wrapFile(shared(_iobuf)* f);
Unsafe function that wraps an existing FILE*. The resulting File never takes the initiative in closing the file.

shared(_iobuf)* getFP();
Returns the FILE* corresponding to this object.

const int fileno();
Returns the file number corresponding to this object.

alias KeepTerminator;
struct ByLine(Char,Terminator);
Range that reads one line at a time.

ByLine!(Char,Terminator) byLine(Terminator = char, Char = char)(KeepTerminator keepTerminator = KeepTerminator.no, Terminator terminator = '\x0a');
Convenience function that returns the LinesReader corresponding to this file.

struct ByChunk;
Range that reads a chunk at a time.

const @property bool empty();
nothrow @property ubyte[] front();
void popFront();
Range primitive operations.

ByChunk byChunk(size_t chunkSize);
Iterates through a file a chunk at a time by using foreach.

Example:
void main()
{
  foreach (ubyte[] buffer; stdin.byChunk(4096))
  {
    ... use buffer ...
  }
}
The content of buffer is reused across calls. In the example above, buffer.length is 4096 for all iterations, except for the last one, in which case buffer.length may be less than 4096 (but always greater than zero).

In case of an I/O error, an StdioException is thrown.

struct LockingTextWriter;
Range that locks the file and allows fast writing to it.

void put(A)(A writeme);
void put(C)(C c);
Range primitive implementations.

LockingTextWriter lockingTextWriter();
Convenience function.

@property ulong size();
Get the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.

void write(T...)(T args);
For each argument arg in args, format the argument (as per to!(string)(arg)) and write the resulting string to args[0]. A call without any arguments will fail to compile.

Throws:
In case of an I/O error, throws an StdioException.

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.

void writef(T...)(T args);
If the first argument args[0] is a FILE*, use the format specifier in args[1] to control the formatting of args[2..$], and write the resulting string to args[0]. If arg[0] is not a FILE*, the call is equivalent to writef(stdout, args).

IMPORTANT:
New behavior starting with D 2.006: unlike previous versions, writef (and also writefln) only scans its first string argument for format specifiers, but not subsequent string arguments. This decision was made because the old behavior made it unduly hard to simply print string variables that occasionally embedded percent signs.

Also new starting with 2.006 is support for positional parameters with POSIX syntax.

Example:
writef("Date: %2$s %1$s", "October", 5); // "Date: 5 October"
The positional and non-positional styles can be mixed in the same format string. (POSIX leaves this behavior undefined.) The internal counter for non-positional parameters tracks the popFront parameter after the largest positional parameter already used.

New starting with 2.008: raw format specifiers. Using the "%r" specifier makes writef simply write the binary representation of the argument. Use "%-r" to write numbers in little endian format, "%+r" to write numbers in big endian format, and "%r" to write numbers in platform-native format.

void writefln(T...)(T args);
Equivalent to writef(args, '\n').

uint readf(A...)(in char[] format, A args);
Formatted read one line from stdin.

string readln(dchar terminator = '\x0a');
size_t readln(ref char[] buf, dchar terminator = '\x0a');
Read line from stream fp.

Returns:
null for end of file, char[] for line read from fp, including terminating character

Parameters:

Throws:
StdioException on error

Example:
Reads stdin and writes it to stdout.
import std.stdio;

int main()
{
    char[] buf;
    while ((buf = readln()) != null)
        write(buf);
    return 0;
}

shared(_iobuf)* popen(in char[] name, in char[] mode = "r");
Convenience function that forwards to std.c.stdio.popen with 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 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.

struct chunks;
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 of buffer is reused across calls. In the example above, buffer.length is 4096 for all iterations, except for the last one, in which case buffer.length may be less than 4096 (but always greater than zero).

In case of an I/O error, an StdioException is thrown.

class StdioException: object.Exception;
Thrown if I/O errors happen.

Member Quick Reference
Member NameDescription
Uncategorized
errnoOperating system error code.
opCallConvenience functions that throw an StdioException.
uint errno;
Operating system error code.

this(string message, uint e = cast(uint)getErrno());
Initialize with a message and an error code.

static void opCall(string msg);
static void opCall();
Convenience functions that throw an StdioException.