如何在fortran的do-loop的每个步骤中读取连续的文本文件行



我有一个包含30个物种参数值的数据集,我想运行一个脚本,对每个物种进行模拟。参数值当前存储在.txt文件中,其中每行是一个不同的种类,每列是一个不同的参数值。我想做的是建立一个do-loop,读取每个物种的相关参数值行,运行模拟脚本,并为每个物种的输出写一个.txt文件。不幸的是,我是fortran的新手,在理解如何在do循环的每个步骤中从.txt文件中连续读取行时遇到了很多麻烦。我尝试制作一个简化的脚本来测试读取步骤是否工作:

    PROGRAM DRIVER
    IMPLICIT NONE
    INTEGER :: mm ! I forgot this line in the first version of this question   
    and edited to add it in
    CHARACTER(7) :: species  !! the first column is the species name
    REAL*8    :: leaf_variable   !  The next 3 columns are variable values
    REAL*8    :: stem_variable   !  
    REAL*8    :: root_variable   !  
    OPEN (12, file = "species_parameters.txt") ! open the .txt file
    DO mm = 1,30 ! set up the do loop
        READ (12,*) species, leaf_variable, stem_variable, root_variable
        ! Read in the species-specific parameter values
        WRITE (*,*) species, leaf_variable, stem_variable, root_variable
        ! Print the values on the screen just to show the do loop runs
    ENDDO
    END PROGRAM DRIVER

但是当我去编译时,我得到了错误:在文件XX的第XX行(unit = 12, file = 'species_parameters.txt')Fortran运行时错误:End of file

我对打开和读取这个文件有什么误解吗?

非常感谢你的帮助。

编辑:我想我已经缩小了我的问题范围。我的理解是read()每次接收.txt文件中的一行,因此在本例中:
    read(7, *) species, leaf_variable, stem_variable, root_variable
    read(7, *) species, leaf_variable, stem_variable, root_variable

变量应该等于.txt文件第二行中的值。相反,无论我在read()函数中输入多少次,变量值都等于第一行。而且,即使只有4列,我也可以用read()函数定义任意多的变量:

   read(7, *) species, leaf_variable, stem_variable, root_variable, 
            fake_variable1, fake_variable2, fake_variable3, fake_variable4

,其中fake_variable的值等于.txt文件第二行中的值。我是否对read()的作用感到困惑,或者我需要做些什么来阻止我的脚本将整个.txt文件读取为一行?

编辑#2:do循环正确地逐行读取,现在我已经使用TextWrangler保存了Unix编码的.txt文件。原始文件用Excel保存为。txt文件。这似乎已经解决了这个问题,但如果有人有更好的方法来指定输入文件格式的建议,我将不胜感激。输入文件的前几行如下所示:
    species1,1.2,6.54,10.9
    species2,1.42,3.5,8.23
    species3,0.85,2.41,4.9 

运行时错误是当您有一个可执行文件,执行它时,它崩溃了。编译时错误是指编译器无法生成可执行文件。

这段代码不应该编译,因为您有IMPLICIT NONE,但没有声明整数mm

我的建议是获取更多的信息:

program driver
    use iso_fortran_env
    implicit none
    character(len=7) :: species
    real(kind=real64) :: leaf_variable, stem_variable, root_variable
    integer :: u, ioerr
    character(len=120) :: iomsg
    open(newunit=u, file='species_parameters.txt', action='read', status='old', iostat=ioerr, iomsg=iomsg)
    if (ioerr /= 0) then
        print *, "Error opening file"
        print *, trim(iomsg)
        stop 1
    end if
    do
        read(u, *, iostat=ioerr, iomsg=iomsg) species, leaf_variable, stem_variable, root_variable
        if (ioerr /= 0) exit  ! exits the loop
        write(*, *) species, leaf_variable, stem_variable, root_variable
    end do
    print *, trim(iomsg)
    close(u)
end program driver

这将总是打印"read past end of file"错误,但这只是检查如何编程读取。

这应该可以编译,当你运行它时,它应该会给你一些关于哪里出错的信息。

最新更新