Input and Output

We have described input and output methods as they have become necessary in earlier tutorials, but this tutorial collates the information and presents the topic in greater depth. We cover input from the keyboard or from a file and output to a monitor, file or printer.

In some implementations of Pascal, programs are declared using the format

program Calculator (input, output);

where the standard input and output are set up by the operating system. Usually, the standard input is the keyboard and the standard output is the monitor (console). In Delphi and Lazarus, the bracketed part of the program declaration is not necessary but is accepted.

The tutorial includes writing to a file with a statement such as write(MyFile, MyVariable) then reading from the file with the corresponding statement read(MyFile, MyVariable). Standard input and output are treated as if they are files. When we use code such as readln(Surname), the standard input is implied by the absence of the file parameter. Try confirming that a statement such as readln(input, Surname) is accepted. Since standard input is treated as a file, you can use the eoln (end of line) and eof (end of file) functions with it.

You have the choice of saving your data either as a textfile or as a typed file such as file of integer. Each choice has pros and cons. You can read a textfile to check its contents when you open it with a text editor but you need to process it serially (starting at the beginning and reading its contents in order). The append procedure to add data to the end of a file applies to a textfile but not to a typed file. A file of integer is not meaningful when viewed in a text editor but it has the advantage that you can use the seek function for random access to any of its data items.

The programs in the Input from File section are based on the output from the Output to File section. We advise you to work through the sections in order. We demonstrate the use of files of records in sections of the Records and Lists Stacks and Queues tutorials.

Follow the links to sections showing you how to write code for input and output.

Programming - a skill for life!

Pascal Programming Tutorials