Question

Basically I am looking to enter X,Y pairs read from a file into arrays of length n where n is the number of lines(and thus x,y pairs) in the file. Unfortunately all my attempts at determining the length of the file then using that to set the size of the array have been unsuccessful. How can I accomplish this in Fortran 77? Hoping I am not missing something obvious, I am more used to Python and Java where this is rather trivial.

PS. Before asking this I looked around and it seemed that the general feeling was that you just set the size larger then you would expect it to be but that seems very memory wasteful and inefficient.

Était-ce utile?

La solution

The solution is to use Fortran 90/95/2003/2008, which has the capabilities needed for your problem, while FORTRAN 77 doesn't. Read the file once to determine the number of data items. Rewind the file. Allocate the array of the required length. Read the file again, reading into the arrays.

Using Fortran 2003/2008 (not tested):

use iso_fortran_env

real :: xtmp, ytmp
real, dimension (:), allocatable :: x, y
integer :: i, n
integer :: Read_Code

open (unit=75, file=...)

n = 0
LengthLoop: do

   read ( 75, *, iostat=Read_Code)  xtmp, ytmp

   if ( Read_Code /= 0 ) then
      if ( Read_Code == iostat_end ) then
         exit LengthLoop
      else
         write ( *, '( / "read error: ", I0 )' )  Read_Code
         stop
      end if
   end if

   n = n + 1

end do LengthLoop

allocate (x(n))
allocate (y(n))

rewind (75)

do i=1, n
   read (75, *) x(i), y(i)
end do

close (75)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top