Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(len=*), | intent(in) | :: | fname | |||
character(len=1), | intent(in), | optional | :: | status |
integer function open_file(fname, status)
! This function opens a file and returns the unit id (a free unit number between 21-1000,
! if file open was successful. The file status remains open!
! If file opening was not successful, the functions stops the programme and closes the file.
character(len=*), intent(in) :: fname
! r for reading, w for writing
character(len=1), intent(in), optional :: status
character(len=1) :: st
integer :: opensucc
integer ui, iostat
logical opened
st = 'r'
if (present(status)) st = status
! get free unit id
do ui = 21, 1000
inquire(unit = ui, opened = opened, iostat = iostat)
if (iostat .ne. 0) cycle
if (.not. opened) exit
end do
open_file = ui
! open file
if (trim(st) == 'r') then
open(ui, file=trim(fname), status='OLD', IOSTAT=opensucc)
else if (trim(st) == "w") then
open(ui, file=trim(fname), IOSTAT=opensucc)
endif
if (opensucc /= 0) then
close(ui)
call log_error("open_file", "ERROR while opening file: "//trim(fname)//" does it exist?")
end if
end function open_file