E.2. Redirecting Input/Output on UNIX/LINUX/Mac OS X and Windows Systems
Normally, the input to a program is from the keyboard (standard input), and the output from a program is displayed on the screen (standard output). On most computer systemsUNIX, LINUX, Mac OS X and Windows systems in particularit is possible to redirect inputs to come from a file, and redirect outputs to be placed in a file. Both forms of redirection can be accomplished without using the file-processing capabilities of the standard library.
There are several ways to redirect input and output from the UNIX command line. Consider the executable file sum that inputs integers one at a time, keeps a running total of the values until the end-of-file indicator is set, then prints the result. Normally the user inputs integers from the keyboard and enters the end-of-file key combination to indicate that no further values will be input. With input redirection, the input can be stored in a file. For example, if the data are stored in file input, the command line
$ sum < input
causes program sum to be executed; the redirect input symbol (<) indicates that the data in file input (instead of the keyboard) is to be used as input by the program. Redirecting input in a Windows Command Prompt is performed identically.
Note that $ represents the UNIX command-line prompt. (UNIX prompts vary from system to system and between shells on a single system.) Redirection is an operating-system function, not another C++ feature.
The second method of redirecting input is piping. A pipe (|) causes the output of one program to be redirected as the input to another program. Suppose program random outputs a series of random integers; the output of random can be "piped" directly to program sum using the UNIX command line
$ random | sum
This causes the sum of the integers produced by random to be calculated. Piping can be performed in UNIX, LINUX, Mac OS X and Windows.
Program output can be redirected to a file by using the redirect output symbol (>). (The same symbol is used for UNIX, LINUX, Mac OS X and Windows.) For example, to redirect the output of program random to a new file called out, use
$ random > out
Finally, program output can be appended to the end of an existing file by using the append output symbol (>>). (The same symbol is used for UNIX, LINUX, Mac OS X and Windows.) For example, to append the output from program random to file out created in the preceding command line, use the command line
$ random >> out