IO redirection

Redirection

To read from an input file instead of typing the input in.

program < input

To send the output to an output file, this is hard to figure out if the program is interactive, since the prompts go to the output file.

program > output

To append the output to an output file

program >> output

Read the input from the input file, put the output to the output file.

program < input > output

Some programs output data to stderr not stdout ( the compiler is an example ). If you want to capture the compiler warnings in a text file try this.

g++ program.cpp >& file.txt

This puts the output to standard out and the output file, allowing you to see and store your output at the same time. The "|" is called a pipe, and it pipes the output of your program to another program. The other program will treat the input as if it came from stdin ( the keyboard/terminal ). In this case the output from "program" is read as input by the program "tee" ( tee puts all of the input to the screen and to a file ).

program | tee output

Read the input from the input file, put the output to the output file, and put output to standard out.

program < input | tee output

Another way to capture output is to use the unix command 'script'. when you have finished type exit, and everything from the command script until exit will be in a text file.

When you read input from any input device/stream there will be an end of file, called eof. You can check for eof in C++. The call 'cin.eof()' would return true when the eof is from the keyboard. In Unix and control-D is eof, it is control-Z in dos/windows.