# Fortran Wiki newunit

This is a simple but useful free-unit locator.

! This is a simple function to search for an available unit.
! LUN_MIN and LUN_MAX define the range of possible LUNs to check.
! The UNIT value is returned by the function, and also by the optional
! argument. This allows the function to be used directly in an OPEN
! statement, and optionally save the result in a local variable.
! If no units are available, -1 is returned.
integer function newunit(unit)
integer, intent(out), optional :: unit
! local
integer, parameter :: LUN_MIN=10, LUN_MAX=1000
logical :: opened
integer :: lun
! begin
newunit=-1
do lun=LUN_MIN,LUN_MAX
inquire(unit=lun,opened=opened)
if (.not. opened) then
newunit=lun
exit
end if
end do
if (present(unit)) unit=newunit
end function newunit

Here is an example, including the function interface. You can put the above unit into a module, or avoid modules and put the interface into an INCLUDE file. Or, make the argument non-optional and just use an EXTERNAL interface.

program test_program
interface
integer function newunit(unit)
integer, intent(out), optional :: unit
end function newunit
end interface
integer lun
open(unit=newunit(lun),file='test')
end program test_program

In Fortran 2008, a NEWUNIT specifier is introduced. It opens a file on an unused unit number (automatically chosen). It also returns the unit number that was chosen. Source: Fortran 2008 Feature Overview, p.11

program test_program
integer :: unit
open(newunit=unit,file='test')
end program test_program

category: code