Fortran:读取多个空格文件

时间:2014-12-08 12:46:13

标签: fortran fortran90

我尝试读取文件(这里的数字相同只是为了了解文件的格式):

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

我的代码是以下代码:

案例1

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 

问题是在阅读期间给我forrtl: severe (24): end-of-file during read的两组不同数据之间的空格。

所以我解决了这个问题只是说代码文件有多少行,我修改代码:

案例2

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 

我的问题是:有没有办法修改CASE 1中的迭代过程,例如我也可以自动读取空行?

1 个答案:

答案 0 :(得分:1)

计算非空行的最小变化。如果需要或必要,可以添加更多检查。

    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

通常情况下,我更喜欢使用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
相关问题