Clicky

Fortran Wiki
newunit (Rev #4, changes)

Skip the Navigation Links | Home Page | All Pages | Recently Revised | Authors | Feeds | Export |

Showing changes from revision #3 to #4: (追記) Added (追記ここまで) | (削除) Removed (削除ここまで) | (削除) Chan (削除ここまで)(追記) ged (追記ここまで)

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(追記) = (追記ここまで)(追記) newunit (追記ここまで),file='test')
end program test_program

category: code

Revision from April 28, 2013 09:50:20 by Anonymous Coward
Forward in time (to current) | Back in time (3 more) | See current | Hide changes | History | Rollback | View: Source | Linked from: Code

AltStyle によって変換されたページ (->オリジナル) /