Previous: 3.4.1 Standard Files and EOF
Up: 3.4 Interacting with the Operating System
Previous Page: 3.4.1 Standard Files and EOF
Next Page: 3.5 Debugging Guidelines

3.4.2 Standard Files and Redirection

As we stated, normally the standard input and standard output files are defined by default to be the keyboard and the screen. This may not always be convenient. For example, in our nice day program, we might want to gather statistics for an entire year of temperature data, or an entire decade. While we may have all this data readily available in a file, to use our program we would have to type it all in at the keyboard again (and what happens if we make a mistake and have to start all over). Operating systems such as Unix and MS-DOS allow a user to redirect the standard input and output files to files other than the keyboard and screen.

If our program in file, niceday.c were compiled using the command:

cc -o niceday niceday.c
producing the executable file niceday, we can execute the program with input data from a file called temperatures by typing the following command to the shell:
niceday < temperatures
The symbol < in the command redirects the standard input to come from the file temperatures instead of the keyboard.

Similarly, we can redirect the standard input to our payroll program, pay5, from a file containing monthly data for many employees:

pay5 < pay_data.march
However, in this case, unless we can read very fast, most of the output generated by the program will scroll past the screen before we can read it. In addition, we might want to save the results of our program execution in a file to send to a printer for a hard copy. A similar redirection of the standard output to a file can be done with the symbol > as follows:
pay5 < pay_data.march > pay_results.march

One problem remains with this technique: all output generated by the program from printf() statements will be redirected to the file, including the prompts we put in the program. In this case, the prompts are not necessary since the data is coming from a file, not from the user at the keyboard. For programs who's input and output are meant to be redirected from/to files, it is best to remove the printf() statements which produce prompts. We might even consider using conditional compilation to include or exclude the prompts, but remember, the program must be recompiled to change from one which prompts to one which does not, and vice versa.



Previous: 3.4.1 Standard Files and EOF
Up: 3.4 Interacting with the Operating System
Previous Page: 3.4.1 Standard Files and EOF
Next Page: 3.5 Debugging Guidelines

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:21:42 HST 1994