在fortran获得免费单位号码

Ste*_*ini 11 fortran fortran95

我需要开发一个库来打开文件并解析这些东西.由于fortran IO风格,单位编号必须由我决定,但我不知道客户端代码中打开了哪些其他单位.有标准功能give_me_any_unit_number_that_is_free()吗?

Jon*_*rsi 28

在fortran 2008中,有一个newunit子句可以打开,你可以使用

   integer :: myunit

   ..
   open(newunit=myunit,file='file.dat')
   ...
   close(myunit)
Run Code Online (Sandbox Code Playgroud)

但这是新的,并非所有编译器都支持它.如果你还没有,你可以自己嘲笑一个; 在fortran维基上有一个很好的例子.


小智 10

您可以使用INQUIRE查找未使用的单元号:

      integer*4 function get_file_unit (lu_max)
!
!   get_file_unit returns a unit number that is not in use
      integer*4 lu_max,  lu, m, iostat
      logical   opened
!
      m = lu_max  ;  if (m < 1) m = 97
      do lu = m,1,-1
         inquire (unit=lu, opened=opened, iostat=iostat)
         if (iostat.ne.0) cycle
         if (.not.opened) exit
      end do
!
      get_file_unit = lu
      return
      end function get_file_unit
Run Code Online (Sandbox Code Playgroud)