next up previous contents
Next: Problem Solving with Numbers Up: Reading from a ``File'' Previous: eof   Contents

Standard Input and Standard Output

Let us consider a very simple program as follows.

var
  number1, number2 : integer;
begin
  read(number1, number2);
  writeln(number1+number2)
end.

As you quickly realize, this program reads two integers, add them up and print the sum to the output.

At this point, you have a program that reads from the keyboard and prints to the screen. This program, however, can be used without any keyboard/screen interaction. It turns out read and readln read from a ``standard input'' file. Similarly, writeln writes to a ``standard output'' file. Normally, the standard input file is the keyboard, and the standard output file is the screen.

There are cases in which you don't want to interact with a program. Consider a grading program that takes answers from an exam. and output the scores for each student. It is more convenient if the program can read the answers from a file created by the ScanTron machine instead. It is also more convenient if the output can be sent directly to a spreadsheet file.

In order to do this, you should read section 2.3 first. This is because the IDE (integrated development environment) does not usually allow you to change the standard input and output files.

Go ahead and run this program from a DOS command line interface. You can expect the same behavior as in the IDE. Now here comes the fun part.

Create a text file with one line, and write two numbers on that line, for example:

56 109

Let us assume this file is called input.txt and it is in the same directory as the program itself. Let us also assume the program is called sum.pas, which creates a file called sum.exe after you successfully compile the program.

Now, type the following (verbatim) in a DOS command line interface:

sum < input.txt

Do you need to type the input? What is the output of the program?

Now, this step is even more fun:

sum < input.txt > output.txt

Where is the output? What is the content of output.txt?

The less than sign, < has a special meaning on a command line. It redirects the standard input file of the program to the file specified to the right of <. Instead of reading from the keyboard, the redirection tells the program to read from the specified file instead.

Similarly, the greater than sign, >, redirects the standard output file to the file specified to the right of >. With this redirection, the program writes to the specified file instead of the screen.


next up previous contents
Next: Problem Solving with Numbers Up: Reading from a ``File'' Previous: eof   Contents
Tak Auyeung 2003-12-03