okay i have a file that looks like this:
2 3
6 6 22
-1 3 0
the integers in the first row are the dimensions of the matrix (not to be included in the matrix)
the rows below the dimensions are the actual matrix
i am trying to write a program that stores this matrix into a 2D array but i keep getting a runtime error when i try to read in the matrix with the nested do loop. It keeps saying “fortran runtime error: end of file” here is my code
PROGRAM addsub
IMPLICIT NONE
CHARACTER(30)::file1
INTEGER:: i,j,err1
INTEGER, DIMENSION(1)::dim1r,dim1c
REAL, ALLOCATABLE:: array1(:,:)
WRITE(*,101) "What is the first filename?"
READ(*,*) file1
OPEN (UNIT=11, FILE=file1, STATUS="OLD", ACTION="READ", IOSTAT=err1)
IF (err1 .NE. 0) THEN
WRITE(*,'(2A)')"There was an error opening ", file1
STOP
END IF
DO i=1,1,1
READ(11,*)dim1r(1),dim1c(1)
END DO
ALLOCATE(array1(dim1r(1),dim1c(1)))
REWIND(11)
DO i=1,dim1r(1),1
DO j=1,dim1c(1),1
READ(11,*) array1(i,j)
END DO
END DO
END PROGRAM addsub
The main problem is that each of your
READstatements are trying to read a separate line; so you’re trying to read 6 lines, and your file doesn’t have that many.There’s a few ways around this:
You can try to read each number one at a time using
advance='no', but that means you can’t use list-directed input and need to use formatting explicitly:You can use implied do loops to read an entire row at once:
Or just have read deal with it by giving it the array slice:
Note another couple of things —
dim1canddim1rdon’t have to be arrays; and you shouldn’tREWINDafter reading the header, or else you’ll read the header in as data.So a complete working version looks like this: