open_file Subroutine

public subroutine open_file(lun, filename_cptr, ierr) bind(C)

Open a new file associated with a specified logical unit number.

Arguments

Type IntentOptional Attributes Name
integer(kind=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(kind=c_int), intent(out) :: ierr

Error code returned by iostat.


Calls

proc~~open_file~~CallsGraph proc~open_file open_file interface~strlen strlen proc~open_file->interface~strlen

Variables

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

Source Code

   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