Reading an array from a text file with Fortran 90/95

If you’re used to coding in more modern languages, Fortran I/O can seem a little bizarre.  Strings in Fortran are much more difficult to work with, since they are fixed-length rather than null-terminated. The following example illustrates a simple way to read an array of numbers from a text file when the array length is unknown at compile time.

program io_test
      real, dimension(:), allocatable :: x
      integer :: n
 
      open (unit=99, file='array.txt', status='old', action='read')
      read(99, *), n
      allocate(x(n))
      read(99,*) x
 
      write(*,*) x
end

Here is the text file that the array is read from. The integer on the first line is the number of elements to read from the next line.

10
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0

7 thoughts on “Reading an array from a text file with Fortran 90/95

  1. Giuseppe

    Superb!
    Let me show (below) a slight modification in order to have the oneline string directly stored in a file. Cheers

    program biz
    real, dimension(:), allocatable :: x
    integer :: n

    open (unit=89, file=’447mono.dat’, status=’new’, action=’write’)
    open (unit=99, file=’447km.dat’, status=’old’, action=’read’)
    read(99, *), n
    allocate(x(n))
    read(99,*) x

    write(89,*) x
    end

    Reply
    1. Martin

      Oh, sorry, I got it… but having to specify the size of the array in the first line of the text won’t work for me… but indeed, this is a simple method…

      Reply
  2. Ade

    Hi martin, am having similar problem, it works fine if i specify the size of the array. Please I need to obtain the length of the array without specifing the size at the beginning,please How do i go about it.

    Reply
    1. Craig Post author

      Ade, you have to know the length of the data before reading it into an array. This is a fundamental limitation of Fortran. If you have to read files of unknown length, you will have to read each file twice. Read a file once to determine the length, allocate the array, and then read in the data.

      Reply
  3. nivas

    Run through the file once to get the no of lines.

    open(99,file='447mono.dat')
    n=0
    do
      read(99,*, iostat=iostatus)dummyv 
      if(iostatus/=0) then ! to avoid end of file error.
        exit
      else
        n=n+1
      end if
    end do 
    allocate (x(n))

    Here n contains the no of lines in the data file.
    Later n can be used in several ways. To read the data in to array now,

    open(99,file='447mono.dat')
    do i=1,n
      read(99,*)array(i)
    end do
    Reply

Leave a Reply