Search code examples
arraysfile-iofortrando-loops

How to avoid skipping input with Fortran READ statement


I am using an old program written in Fortran. There is a section of the program that reads data from a file into a 2d array via an implied do loop. The file contains data corresponding to points on a 2d cartesian grid with dimension nx by ny. The format of the file is

 900  FORMAT(6F10.6)

i.e. 6 columns with format 10.6f followed by a newline. The file therefore has nx*ny/6 lines. The data is read into a 2d array, which has been defined by

      DIMENSION A(NY,NX)

via the loop

      OPEN (UNIT=33,STATUS=OLD)
      DO 100 J=1,NX
      READ(33,900) (A(I,J),I=1,NY)
 100  CONTINUE

My problem is that this only works if the number of lines nx*ny/6 is integer. Otherwise after each ny reads, the implied do loop skips the rest of the line and starts on the next line. Therefore, the end of the file is reached before the array has been filled and

Fortran runtime error: End of file

is thrown.

I am not experienced with Fortran and diagnosed this error through a few print statements. After reading some online tutorials, I haven't managed to figure out how to change the read loop to not skip data points if not at the end of a line. I'd be very grateful for a hint.

Thanks in advance.


Solution

  • Each new READ operator starts to read data from a new line. That is a reason why your code does not work properly, as you expected.

    If the @lastchance's solution READ (33,*) A will work - it is OK. If not, the straightforward way will be just to make a cycle until end-of-file or until nx*ny numbers is read. At each cycle iteration you would read six (or less) numbers and put them in the corresponding matrix entries.