1 /**
2  * Copyright: Copyright Jason White, 2014-2016
3  * License:   $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4  * Authors:   Jason White
5  *
6  * Description:
7  * Provides access to the standard I/O streams: $(D stdin), $(D stdout), and $(D
8  * stderr). Note that each of these streams are buffered.
9  *
10  * To avoid conflict with $(D std._stdio), the file handles of each stream are
11  * duplicated on static construction and closed upon static destruction.
12  */
13 module io.file.stdio;
14 
15 import io.file.stream;
16 import io.buffer.fixed;
17 
18 __gshared
19 {
20     /**
21      * Standard input stream.
22      *
23      * Example:
24      * Counting the number of lines from standard input.
25      * ---
26      * import io;
27      * size_t lines = 0;
28      * foreach (line; stdin.byLine)
29      *     ++lines;
30      * ---
31      */
32     File stdin;
33 
34     /**
35      * Standard output stream.
36      *
37      * Example:
38      * ---
39      * import io;
40      * stdout.write("Hello world!\n");
41      * stdout.flush();
42      * ---
43      */
44     File stdout;
45 
46     /**
47      * Standard error stream.
48      *
49      * stderr is often used for writing error messages or printing status
50      * updates.
51      *
52      * Example:
53      * Prints a useful status message.
54      * ---
55      * import core.thread : Thread;
56      * import core.time : dur;
57      *
58      * immutable status = `|/-\`;
59      *
60      * for (size_t i = 0; ; ++i)
61      * {
62      *     Thread.sleep(dur!"msecs"(100));
63      *     stderr.write("Reticulating splines... ");
64      *     stderr.write([status[i % status.length], '\r']);
65      *     stderr.flush();
66      * }
67      * ---
68      */
69     File stderr;
70 }
71 
72 shared static this()
73 {
74     // Initialize stdio streams.
75     version (Posix)
76     {
77         import core.sys.posix.unistd : dup;
78         stdin  = File.dup(0);
79         stdout = File.dup(1);
80         stderr = File.dup(2);
81     }
82     else version (Windows)
83     {
84         import core.sys.windows.windows;
85         stdin  = File.dup(GetStdHandle(STD_INPUT_HANDLE));
86         stdout = File.dup(GetStdHandle(STD_OUTPUT_HANDLE));
87         stderr = File.dup(GetStdHandle(STD_ERROR_HANDLE));
88     }
89 }
90 
91 shared static ~this()
92 {
93     stderr.flush();
94     stdout.flush();
95 }