Open a new file associated with a specified logical unit number.
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer(kind=c_int), | intent(inout) | :: | lun |
Logical unit number. If |
||
type(c_ptr), | intent(in), | value | :: | filename_cptr |
C-string containing the file name. |
|
integer(kind=c_int), | intent(out) | :: | ierr |
Error code returned by |
Type | Visibility | Attributes | Name | Initial | |||
---|---|---|---|---|---|---|---|
character(kind=c_char, len=1), | public, | pointer | :: | filename_fptr(:) | |||
character(len=:), | public, | allocatable | :: | filename | |||
character(len=256), | public | :: | errmsg | ||||
integer, | public | :: | length | ||||
integer, | public | :: | i |
subroutine open_file(lun, filename_cptr, ierr) bind(C) !! Open a new file associated with a specified logical unit number. integer(c_int), intent(inout) :: lun !! Logical unit number. If `lun > 0`, the user-supplied logical unit number is used. !! Otherwise, a new logical unit number is assigned. type(c_ptr), intent(in), value :: filename_cptr !! C-string containing the file name. integer(c_int), intent(out) :: ierr !! Error code returned by `iostat`. character(kind=c_char), pointer :: filename_fptr(:) character(len=:), allocatable :: filename character(len=256) :: errmsg integer :: length, i length = strlen(filename_cptr) allocate (filename_fptr(length)) call c_f_pointer(cptr=filename_cptr, fptr=filename_fptr, shape=[length]) allocate (character(len=length) :: filename) do i = 1, length filename(i:i) = filename_fptr(i) end do if (lun > 0) then open (file=filename, unit=lun, status='replace', iostat=ierr, iomsg=errmsg) else open (file=filename, newunit=lun, status='replace', iostat=ierr, iomsg=errmsg) end if if (ierr /= 0) then print *, "I/O error: ", trim(errmsg) end if end subroutine open_file