Handling End-of-File: the READ Statement Revisited

In many situations, you really do not know the number of items in the input. It could be so large to be counted accurately. Consequently, we need a method to handle this type of input. In fact, you have encountered such a technique in Programming Assignment 1 in which a keyword IOSTAT= was used in a READ statement. The following is its syntax:

INTEGER :: IOstatus

READ(*,*,IOSTAT=IOstatus) var1, var2, ..., varn
The third component of the above READ is IOSTAT= followed by an INTEGER variable. The meaning of this new form of READ is simple:

After executing the above READ statement, the Fortran compiler will put an integer value into the integer variable following IOSTAT=, IOstatus above. Based on the value of IOstatus, we have three different situations:

  1. If the value of IOstatus is zero, the previous READ was executed flawlessly and all variables have received their input values. This is the normal case.
  2. If the value of IOstatus is positive, the previous READ has encountered some problem. In general, without knowing the system dependent information, it is impossible to determine what the problem was. However, if hardware and I/O devices are working, a commonly seen problem would be illegal data. For example, supplying a real number to an integer variable. If IOstatus is positive, you cannot trust the values of the variables in the READ statement; they could all contain garbage values, or some of them are fine while the others are garbage.
  3. If the value of IOstatus is negative, it means the end of the input has reached. Under this circumstance, some or all of the variables in the READ may not receive input values.

What is the end of file? How do we generate it? If you prepare your input using a file, when you save it, the system will generate a special mark, called end-of-file mark, at the end of that file. Therefore, when you read the file and encounter that special end-of-file mark, the system would know there is no input data after this mark. If you try to read passing this mark, it is considered as an error.

If you prepare the input using keyboard, hiting the Ctrl-D key would generate the end-of-mark under UNIX. Once you hit Ctrl-D, the system would consider your input stop at there. If your program tries to read passing this point, this is an error.

However, with IOSTAT=, you can catch this end-of-file mark and do something about it. A commonly seen application is that let the program to count the number of data items as will be shown in examples below.

Examples