16. Simple I/O

An important part of any computer program is the handling of input and output. In our examples so far, we have already used the two most common Fortran constructs for this: read and write. Fortran I/O can be quite complicated, so we will only describe some simpler cases in this tutorial.

Read and write

Read is used for input, while write is used for output. A simple form is:

      read (unit no, format no) list-of-variables
      write(unit no, format no) list-of-variables

The unit number can refer to either standard input, standard output, or a file. The format number refers to a label for a format statement, which will be described in the next lesson.

It is possible to simplify these statements further by using asterisks (*) for some arguments, like we have done in most of our examples so far. This is sometimes called list directed read/write.

      read (*,*) list-of-variables
      write(*,*) list-of-variables

The first statement will read values from the standard input and assign the values to the variables in the variable list, while the second one writes to the standard output.

Examples

Here is a code segment from a Fortran program:

      integer m, n
      real x, y, z(10)

      read(*,*) m, n
      read(*,*) x, y
      read(*,*) z

We give the input through standard input (possibly through a data file directed to standard input). A data file consists of records according to traditional Fortran terminology. In our example, each record contains a number (either integer or real). Records are separated by either blanks or commas. Hence a legal input to the program above would be:

   -1  100
  -1.0 1e+2
  1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0

Or, we could add commas as separators:

   -1, 100
 -1.0, 1e+2
  1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0

Note that FORTRAN 77 input is line sensitive, so it is important not to have extra input elements (fields) on a line (record). For example, if we gave the first four inputs all on one line as:

   -1, 100, -1.0, 1e+2
  1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0

Then m and n would be assigned the values -1 and 100 respectively, but the last two values would be discarded, x and y would be assigned the values 1.0 and 2.0, ignoring the rest of the second line. This would leave the elements of z all undefined.

If there are too few inputs on a line then the next line will be read. For example

   -1
  100
 -1.0
 1e+2
  1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0

Would produce the same results as the first two examples.

Other versions

For simple list-directed I/O it is possible to use the alternate syntax:

      read  *, list-of-variables
      print *, list-of-variables

Which has the same meaning as the list-directed read and write statements described earlier. This version always reads/writes to standard input/output so the * corresponds to the format.

Copyright © 1995-7 by Stanford University. All rights reserved.

[ Index ]