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:
The third component of the above READ is IOSTAT= followed by an INTEGER variable. The meaning of this new form of READ is simple:INTEGER :: IOstatus READ(*,*,IOSTAT=IOstatus) var1, var2, ..., varn
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:
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.
INTEGER :: Reason INTEGER :: a, b, c DO READ(*,*,IOSTAT=Reason) a, b, c IF (Reason > 0) THEN ... something wrong ... ELSE IF (Reason < 0) THEN ... end of file reached ... ELSE ... do normal stuff ... END IF END DO
Now if the input isINTEGER :: io, x, sum sum = 0 DO READ(*,*,IOSTAT=io) x IF (io > 0) THEN WRITE(*,*) 'Check input. Something was wrong' EXIT ELSE IF (io < 0) THEN WRITE(*,*) 'The total is ', sum EXIT ELSE sum = sum + x END IF END DO
the above code should display 8 (=1+3+4). If the input is1 3 4
since @ is not a legal integer, the second time the READ is executed, io would receive a positive number and the above program exits the DO-loop.1 @ 3