Reputation: 1032
I try to read a file as such (the numbers here are equal just to have an idea of the format of the file):
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
0.7498000E-01 0.1046400E+00 0.4006199E-01 0.1978479E+01
My code is the follow one:
program selection
implicit none
integer :: i,n,s,j
REAL*8,allocatable:: dum1(:),dum2(:),dum3(:),dum4(:)
open(10,file='file.txt')
n=0
DO
READ(10,*,END=100)
n=n+1
END DO
100 continue
rewind(10)
allocate(dum1(n),dum2(n),dum3(n)dum4(n))
s=0
do s=1, n
read(10,*) dum1(s),dum2(s),dum3(s),dum4(s)
end do
end program selection
The problem are the spaces between two different set of data that give to me forrtl: severe (24): end-of-file during read
during the reading.
So I solve this problem just saying to the code how many lines the file has, and I modify the code as such:
program selection
implicit none
integer :: i,n,s,j
REAL*8,allocatable:: dum1(:),dum2(:),dum3(:),dum4(:)
open(10,file='file.txt')
n = 9 ! number of rows in the particular file in this example
allocate(dum1(n),dum2(n),dum3(n)dum4(n))
s=0
do s=1, n
read(10,*) dum1(s),dum2(s),dum3(s),dum4(s)
end do
end program selection
My question is: is there some way to modify the iterative process in CASE 1 such as I can automatically read empty lines, too?
Upvotes: 0
Views: 130
Reputation: 60058
A minimal change to count non-empty lines. More checking can be added if desirable or necessary.
character(max_line_length) :: line
open(10,file='file.txt')
n=0
DO
read(10,'(a)',end=100) line
if (len_trim(line)>0) n = n + 1
END DO
100 continue
Normally, I prefer to stop counting on any end-of-file condition or error-condition using iostat=
)
character(max_line_length) :: line
integer :: ie
open(10,file='file.txt')
n=0
DO
read(10,'(a)',iostat=ie) line
if (ie/=0) exit
if (len_trim(line)>0) n = n + 1
END DO
Upvotes: 1