maxm
maxm

Reputation: 113

Is there a way in Fortran to write to an output file from subroutine when the file has open statement in main program.

In Fortran, I am trying to write to an output file from subroutine when the file has open statement in the main program. In other words, how do I pass file unit number (terminal number) to subroutine from the main program. Any idea about this is highly appreciated.For example, my code looks like this,

program main1
open(unit=11,file='output.dat')
call subroutine1
...
call subroutine1
...
end program main1


subroutine subroutine1
write(11,*)'dummy'
...
write(11,*)'dummy'
...
end subroutine subroutine1

Upvotes: 4

Views: 4494

Answers (1)

Bálint Aradi
Bálint Aradi

Reputation: 3812

By passing the integer representing the opened file:

module mod1
  implicit none
contains
  subroutine subroutine1(fp)
    integer, intent(in) :: fp
    write(fp,*)'dummy'
    write(fp,*)'dummy'
  end subroutine subroutine1
end module mod1

program main1
  use mod1
  implicit none
  integer :: fp
  fp = 11
  open(unit=fp,file='output.dat')
  call subroutine1(fp)
  close(fp)
end program main1

Upvotes: 6

Related Questions