Navigation:  Programming Cookbook > Creating Console Applications >

Accessing Standard I/O Streams

Previous pageReturn to chapter overviewNext page

Many console applications will want to do I/O, and often this will involve reading from the standard input stream (stdin) and writing to the standard output (stdout) and standard error (stderr) streams. These streams, collectively referred to as the stdio streams, can be accessed by sending the messages #stdin, #stdout, or #stderr to the session manager. The objects returned by these accessors implement standard Smalltalk stream protocols such as #next, #nextPut:, #nextPutAll:, #cr and #tab, For example the Hello Word (Console) application is implemented as follows (from the CommandLineHelloWorld class):


       "Implement the main body of the Headless Hello World application

       by printing that familiar greeting to the standard output stream."


       self stdout

       nextPutAll: 'Hello World!'; cr; flush.

       self stderr

       nextPutAll: 'Press <Enter> to exit:'; flush.

       self stdin nextLine


This uses all three stdio streams, mainly for illustrative purposes. The streams are instances of the StdioFileStream, and are connected to stdio streams implemented by the C runtime library (CRT). Note that it is necessary to flush the output streams before any output actually appears because they are buffered by the CRT.

The standard I/O streams are in fact connected to the same streams as used by the CRT and the underlying operating system. Thus if the streams are redirected from the command line, then the input or output from Dolphin will be redirected too. Furthermore, calls to the C runtime library stdio functions such as gets() and printf() will result in input or output to or from the same stream. This makes it possible to employ external libraries that use the standard I/O streams in a completely integrated manner.