next up previous index
Next: Program Explanation Up: Reading Data from Instruments Previous: Reading Data from Instruments

Linked Lists in Fortran

program ptr
  implicit none
  type node
     real :: x, y, sigma
     type (node), pointer :: next
  end type node
  type(node), pointer :: list, first
  integer, parameter :: input_lu = 10
  character(len=8), parameter :: input_file = 'chi2.dat'
  integer status, count, i
  real, dimension(:), allocatable :: x, y, sigma

  open(unit=input_lu, file=input_file, action='read', &
       status='old', iostat=status, err=99)
  write(*,*) 'reading file ', input_file
  allocate(list); nullify(list%next)
  first => list; count = 0
  do
     read(input_lu, fmt='(3f6.2)', end=100) list%x, list%y, list%sigma
     count = count + 1
     allocate(list%next); list => list%next; nullify(list%next)
  end do
100 close(unit=input_lu)
  write(*,*) 'read ', count, ' records'
  write(*,*) 'allocating arrays for data'
  if (count .gt. 0) then
     allocate(x(count)); allocate(y(count)); allocate(sigma(count));
  end if
  write(*,*) 'listing the records and transferring data to the arrays'
  list => first; count = 0
  do while (associated(list%next))  
     write(*, '(3x, 3f6.2)') list%x, list%y, list%sigma
     count = count + 1
     x(count) = list%x; y(count) = list%y; sigma(count) = list%sigma
     list => list%next
  end do
  write(*,*) 'listing the arrays'
  do i = 1, count
     write(*, '(3x, 3f6.2)') x(i), y(i), sigma(i)
  end do
  stop 0
99 write(*,*) 'Error opening file: ', input_file
  write(*,*) 'iostat = ', status
  stop 1
end program ptr



Zdzislaw Meglicki
2001-02-26