Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading an array from a text file in Fortran 90 1

Status
Not open for further replies.

classic35mm

Programmer
Jun 25, 2011
3
US
Hi,

I would like to read an array from a text file. I have created a text file (which I called data.txt) containing the following text:

Code:
1 2 3 4
5 6 7 8
9 10 11 12

I would like to read this in as an array, "row-wise." I have created a Fortran 90 file (which I called myread2.f90) containing the following code:

Code:
PROGRAM myread2
  IMPLICIT NONE

  INTEGER, DIMENSION(3,4) :: a
  INTEGER :: row,col,max_rows,max_cols
  max_rows=3
  max_cols=4

  OPEN(UNIT=11, FILE="data.txt")

  DO row = 1,max_rows
    DO col = 1,max_cols
      READ(11,*) a(row,col)
    END DO
  END DO

  PRINT *, a(1,3)
  PRINT *, a(2,2)
END PROGRAM myread2

I then compile the code, using the GNU Fortran compiler; it seems to compile fine (at least with the default settings). However, when I run the resulting executable, I get the following error message:

At line 13 of file myread2.f90 (unit = 11, file = 'data.txt')
Fortran runtime error: End of file

where line 13 is the line containing [/b]READ(11,*) a(row,col)[/b].

If you have time, can you please help me see what I am doing wrong? Do you think that it is a problem with my text file (data.txt) or with my code?

Thank you very much!
 
You get a trouble because each read statement reads one file line.

Use a single DO loop as follows :

Code:
  DO row = 1,max_rows
      READ(11,*) (a(row,col),col=1,max_cols)
  END DO

François Jacq
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top