getting free unit number in fortran
Asked Answered
K

2

14

I need to develop a library that opens a file and parses the stuff. The unit number, due to fortran IO style, must be decided by me, but I can't know what other units are open in the client code. Is there a standard function like give_me_any_unit_number_that_is_free() ?

Kolosick answered 24/10, 2011 at 13:7 Comment(0)
M
34

In fortran 2008, there's a newunit clause to open that you can use

   integer :: myunit

   ..
   open(newunit=myunit,file='file.dat')
   ...
   close(myunit)

but that's new enough that not all compilers support it yet. If yours doesn't yet, you can mock one up yourself; there's a good example on the fortran wiki.

Mcleroy answered 24/10, 2011 at 13:13 Comment(0)
E
10

You can use INQUIRE to find a unit number that is not in use:

      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
Eau answered 30/11, 2011 at 6:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.