递归子例程中的open语句

时间:2013-08-14 15:50:51

标签: fortran90

我想将结果写入一个在递归子程序中生成的文件中。我还想将文件中的数据(读取)分配给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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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_max。满足此条件会将一行行写入a.dat,然后完成之前if语句的所有。你可能想要的是通过递归循环写入文件每个时间;要做到这一点,你会想要像

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

在执行此操作时,我发现我增加了两行(由于在position=position_minposition=position_max写作)。您可能可以调整它以获得720,但我认为这部分是无关紧要的,因为您可以将read循环更改为以下

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

正常读取返回iostat为0,文件结束返回-1,所以只要你能读,你就会继续循环并在找到EOF时中断。

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

相关问题