InputRedirect

Home Assignments Lecture Blog Resources Discussion Group

Input Redirection

The sample command line in the assignment is:

NBody 157788000.0 25000.0 < planets.txt

This line includes an input redirection operator. This operator is a feature of the operating system. This is how it works:

  1. When the operating system encounters a less than (<) character on the command line, it removes the < character along with following argument from the argv of your program. The argv resulting from the command line above will be as follows:
    • argc equals to 3 (not 5, and not 4, because the < and the planets.txt tokens are removed)
    • argv[0] is NBody
    • argv[1] is 157788000.0
    • argv[2] is 25000.0
  2. The operating system interprets the argument following the < character as a file name. It opens the file, and "magically" connects it to the standard input stream of the program. In C++, this standard input stream is represented by std::cin (and in plain C it is stdin.)
  3. The program then uses e.g the >> operator to read from standard input, but, instead of the console input (the keyboard), it now reads from the file (e.g. planets.txt.)

In other words, the example command line does the same thing as running "NBody 157788000.0 25000.0" (without the redirect), and then typing the contents of the planets.txt file into the terminal!

Usage in PS3

Design your program to read the universe file from standard input std::cin. You do not need to open the file planets.txt. Input redirection will take care of handling this file for you.

Additional info

Input redirection is a feature of the operating system, so it's available for programs written in any language, not just C++. This feature is supported, with the same syntax, on pretty much any major computing platform:

  • Linux, or any other UNIX-like operating system.
  • Microsoft Windows (in a terminal window.)
  • OS X.

A detailed technical description of I/O redirection is available here http://wiki.bash-hackers.org/howto/redirection_tutorial. Note that while the syntax for simple redirection is the same on all operating systems, the more complex redirection operations use different syntax on different OS.