D (The Programming Language)/d2/Hello, World!/More Info about the Write Family

From Wikibooks, open books for an open world
Jump to: navigation, search

More Info about the write Family[edit]

The four functions in the write family in std.stdio are: write, writef, writeln, and writefln. They are based on the C functions from cstdio (the D bindings to them are in core.stdc.stdio) for writing to streams. This subpage assumes that you have solid knowledge of the C standard library.

stdout[edit]

The std.stdio module imports core.stdc.stdio, thereby gaining access to a stream named stdout. Most of the time, stdout is the console, and it is most often line-buffered, even though the type of buffering is actually implementation-defined. So, line-buffering for stdout will be assumed for the rest of this article, even though it is not standard.

The Functions, How They Work[edit]

Map of What Happens[edit]

I. Start here if you are using write. For each argument that write is called with: goto A. with that argument.
A. If the argument is of some string type: goto 1. Else: goto B.
1. If the argument is a char string and fwide(stdout, 0) <= 0: the argument will be passed to fwrite to be written to stdout, flushing will occur if the buffer is full, and maybe if there is a newline in the argument (especially on Linux). Else: goto 2.
2. Each character from the argument is written to stdout by being passed to either fputc or fputwc, depending on whether the character's type. If the buffer becomes full or if the argument is a newline character, flushing will occur.
B. The argument is not of some string type. goto 1.
1. If the argument is some char type: goto I.A.2. Else: goto 2.
2. The argument will be converted to a char string with std.format, goto I.A.1.
II. Start here if you are using writeln. goto A.
A. If there are no arguments: Use fputc to output a newline to stdout. Flushing will occur. Else: goto B.
B. If there is one argument and that argument is a const(char)[] (string) value: use fprintf to print out that string with a newline at the end, and flushing will occur. Else: goto C.
C. If there is more than one argument, or if there is only one argument that is not a string value: Add the char value of '\n' to the end of the arguments list, and then for each argument: goto I.A. with that argument.
III. Start here if you are using writef. goto A.
A. If the the first and only argument is a char: goto I.A.2. with that argument. Else: All the arguments are formatted (C-style) together with std.format, and goto I.A.1. with that result.
IV. Start here if you are using writefln. goto A.
A. If the the first and only argument is a char: goto I.A.2. with each of these two: (that argument, a newline char).
Else: All the arguments are formatted (C-style) together with std.format, and goto I.A.1. with each of these two: (the result from formatting, a newline char).