Fortran: How to read to an array from a file

SharkTiles picture SharkTiles · Nov 6, 2012 · Viewed 13.2k times · Source

I'm trying to read integers from a file to an array. But I get an error when I run the program.

PROGRAM MINTEM

INTEGER TEMP(4,7), I, J, MINIMUM, CURRENT

OPEN(UNIT=1, FILE='temps.dat')
READ (1,*) ((TEMP(I,J),J=1,7),I=1,4)

MINIMUM = TEMP(1,1)
DO I = 1,4
    DO J = 1,7
        IF (TEMP(I,J) < MINIMUM) THEN
            MINIMUM = TEMP(I,J)
        END IF
    END DO
END DO


PRINT *, "MINIMUM TEMPERATURE = ", MINIMUM
END PROGRAM MINTEM

Input file looks like this:

 22
100 90 80 70 60 100 90 80 70 60 100 90 80 70 60 100 90 80 70
100 90

Answer

ev-br picture ev-br · Nov 6, 2012

The file you provided can be read in using this:

integer, allocatable :: t(:)
open(1,file='temp.dat')
read(1,*) N   ! your first line with 22
allocate( t(N-1) )  ! further on you only have 21 elements
read(1,*)t          ! so, read them in 
print*, t
deallocate(t)
close(1)