1

我想将我的结果写入在递归子程序中生成的文件中。而且我还想将文件中的数据(读取)分配给我在fortran90中的主程序中的一个数组。

program permutations
  implicit none

  call generate (position_min)

  open(unit=20, file="a.dat", status="old")
  do i=1,720
     read(20,*)(G(i,j),j=1,6)
  end do
contains
 recursive subroutine generate (position)
   implicit none
   integer, intent (in) :: position
   integer :: value

   if (position > position_max) then
     open(unit=20, file="a.dat", status="unknown")
     write (20, *) permutation
   else
     call generate(position+1)
   end if

 end subroutine generate
end program permutations

该程序给了我以下运行时错误。

At line 19 of file p2.f90 (unit = 20, file = 'a.dat')
Fortran runtime error: End of file

我该如何解决?

4

1 回答 1

0

我认为答案主要是我对这个问题的评论。如果您查看您的代码(忽略未声明的变量问题),特别是if递归子例程的 -statement,您应该注意您有

if (position > position_max) then
  open(unit=20, file="a.dat", status="unknown")
  write (20, *) permutation
else
  call generate(position+1)
end if

也就是说如果. _ 满足此条件将写入一行,然后完成所有先前的语句。您可能想要的是每次通过递归循环写入文件;要做到这一点,你会想要类似的东西 position > position_maxa.datif

open(20,file="a.dat",status="unknown")
write(20,*) permutation
close(20)
if(position > position_max) then
   return
else
   call generate(position+1)
endif

在运行此程序时,我发现我得到了 2 额外的行(由于写 atposition=position_min和 at position=position_max)。您可能可以对其进行调整以获得准确的 720,但我认为这部分无关紧要,因为您可以将read循环更改为以下

i=1
do
   read(20,*,iostat=ierr) G(i,:)
   if(ierr/=0) exit
   i = i+1
enddo

正常读取返回iostat0 并且文件结尾返回 -1,因此只要您可以读取,您将继续循环并在找到 EOF 时中断。

在修复了未声明的变量、添加close(20)语句并按照我上面的评论进行调整之后,我在递归子例程中编写和阅读都没有问题。

于 2013-08-21T01:19:52.820 回答