Example as promised.
implicit none
integer, parameter :: sp = kind(1.0), dp = kind(1.d0)
integer ii, i, j, k
real(kind=sp) asp, bsp
real(kind=dp) adp, bdp
integer, parameter :: n = 10
character(len=50), parameter :: fmt='(I3,1X,I3,1X,F10.5,1X,1X,F10.5,1X,F10.5,1X,F10.5)'
! Note that the format code above will write out a string 52 characters long, so this is now the MINIMUM record length
!
! Integer 3 characters
! One space 1
! Integer 3
! One space 1
! Real 10
! One space 1
! Real 10
! One space 1
! Real 10
! One space 1
! Real 10
! ------
! Total width 52
! ------
open(unit=10, file='martin.txt', status='UNKNOWN', access='DIRECT', recl=52, action='WRITE', FORM='FORMATTED', ERR=90 )
print*
print*, 'Writing to file'
do i = 1, n
write(10,fmt,REC=i,ERR=92) i,i+10, real(i),real(i)+1.0, dble(i), dble(i) + 1.d0
write(6,fmt) i,i+10, real(i),real(i)+1.0, dble(i), dble(i) + 1.d0 ! Echo to screen
end do
close(unit=10, status='keep',ERR=91)
! Open the direct access file
open(unit=11, file='martin.txt', status='OLD', access='DIRECT', recl=52, action='READ', form='FORMATTED', err=90)
print*
print*, 'Reading from file'
do i = 1, n
read(11,fmt,REC=i,err=93) j,k,asp,bsp,adp,bdp
write(6,fmt) j,k, asp, bsp, adp, bdp ! Echo to screen
end do
close(unit=11,status='keep',err=91)
open(unit=11, file='martin.txt', status='OLD', access='DIRECT', recl=52, action='READ', form='FORMATTED', err=90)
print*
print*, 'Reading from file - n random records'
do i = 1, n
ii = int(dble(n)*random@())
if (ii .eq. 0) ii = 1 ! ii is random record to be accessed
read(11,fmt,REC=ii,err=93) j,k,asp,bsp,adp,bdp
print*,'Record', ii
write(6,fmt) j,k, asp, bsp, adp, bdp
end do
close(unit=11,status='keep',err=91)
goto 100
90 STOP 'ERROR opening direct access file'
91 STOP 'ERROR closing direct access file'
92 STOP 'ERROR writing to direct access file'
93 stop 'ERROR reading from direct access file'
100 continue
end program