12. Simple I/O

An important part of any computer program is to handle 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. This will be described in later section. The format number refers to a label for a format statement, which will be described shortly.

It is possible to simplify these statements further by using asterisks (*) for some arguments, like we have done in all 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.


Here is a code segment from a Fortran program:
      integer m, n
      real x, y

      read(*,*) m, n 
      read(*,*) x, y 
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
Or, we could add commas as separators:
   -1, 100
 -1.0, 1e+2
Note that Fortran 77 input is line sensitive, so it is important to have the right number of input elements (records) on each line. For example, if we gave the input all on one line as
   -1, 100, -1.0, 1e+2
then m and n would be assigned the values -1 and 100 respectively, but the last two values would be discarded, leaving x and y undefined.

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.

[AMS Home Page] [Fortran Tutorial Home]