Fortran 查询 return 内部文件

Fortran inquire return internal file

我的 Fortran 程序出现意外情况。 我想将一些数据放入文本文件中。由于某些原因,我创建了一个类型来处理这个文件。

因此,我使用以下命令打开一个文件(其中 f 是我的文件类型对象):

open(newunit    = f%unit,          &
     file       = trim(adjustl(f%name)), &
     form       = 'FORMATTED',      & 
     access     = 'STREAM',         & 
     action     = 'WRITE',          &
     status     = 'REPLACE',        &
     iostat     = ios)
if(ios /= 0) print '("Problem creating file")', trim(f%name)

然后我这样写:

write(unit=f%unit,fmt='(100A)') "#Header"

完成后,我想关闭文件。为此,我调用子例程:

subroutine close_file_ascii(f)    
  implicit none
  class(my_file_type) intent(in) :: f
  logical :: file_opened, file_exist
  integer :: ios

  inquire(unit=f%unit, exist=file_exist, opened=file_opened) !, iostat=ios)
  print *,'file_exist:', file_exist, 'file_opened:', file_opened, 'ios:', ios
  if ((file_opened) .and. (file_exist)) then
     close(unit=f%unit)
  else
    print *,"[WARNING]"
  end if
end subroutine close_file_ascii

我的问题出在最后一个子例程中。当我 运行 windows 上的程序时,出现以下错误:

Fortran runtime error: Inquire statement identifies an internal file
Error termination. Backtrace

因此,我尝试创建 MWE 来理解问题,但它们都运行良好。所以不能真正隔离问题。还有一件奇怪的事情是,当我在我的 linux 上使用 gfortran 编译和执行时没有问题,但是当我在我的 windows 上这样做时,我得到了以前的错误。 (我在 windows 上用 gfortran 版本 7.3.0 x86_64-posix-sjlj-rev0 编译,由 MinGW-W64 构建)

我已经通过在 close 子例程中取消对 inquire 行末尾的注释来解决这个问题,并且一切似乎都工作正常。我得到以下打印:

file_exist: T file_opened: T ios:        5018

但我想了解发生了什么。那么什么会造成这样的内部文件错误(虽然文件不应该是内部的而是外部的)?我的解决方法可能有害吗?这是一个错误吗?有没有更好的方法来安全关闭打开的文件?有什么想法可以隔离问题吗?

编辑

根据 roygvib 的评论,以下测试似乎重现了该问题:

program bug
  implicit none
  integer          :: i
  character(len=1) :: s
  write (s,'(i1)') 0
  open(newUnit=i,file='bug.txt',status='unknown')
  inquire(unit=i)
end program bug

更新到 gfortran 8.1 解决了这个问题。