When a reading a file, it is not difficult to try to read past the end of the file. Sometimes this is unintentional, but other times the only way to find out where the end of the file is located is to try (and fail) to read something.
Consider, for example, the program from the last lesson (``file2.f'') that read and added up ten numbers from a file. What would happen if the file that this program reads contained less than ten lines? Modify the input file so that it contains only nine numbers, run it, and see.
Well, what if we want to write a program that will read all of the numbers from a file, regardless of how many there are, and then print out their sum. What problem would we have doing that?
To find out how we can solve problems of this kind, take a look at ``file5.f'' in your ``examples'' directory (or view it directly). Compare it to ``file2.f'', which you should have left over from the last lesson. How do they differ?
Obviously, it reads a different filename, since you have modified ``file2.f'' to read your own file. Modify ``file5.f'' so that it reads from the same file as ``file2.f''.
Click here for some important differences
Surely this isn't an infinite loop! But how does the program ever get out of it?
Because IOSTAT=ERROR is present, the value of the integer variable ERROR is set each time the READ statement is executed. If the READ statement executes with no problems, ERROR is set to 0. If the READ fails because the end of the file has been reached, ERROR is set to a negative number. If the READ fails for some other reason (for example, if there is a formatting error), ERROR is set to a positive number.
How do we make use of the value of ERROR in ``file5.f''?
Notice that we don't take any corrective action when other kinds of errors occur---our program would be better if we did. We'll see how to do that in the next section.
Hamlet Project