mod0
mod0

Reputation: 155

Accessing open files globally in Fortran

Is there any means to accessing (reading, writing to) files that are opened in some other source code by just passing the unit number?

Upvotes: 1

Views: 353

Answers (2)

casey
casey

Reputation: 6915

External file units are globally accessible. You need not even pass the unit number, though that is a better practice than using hardcoded units. This behavior defined in Fortran 2008 Cl. 9.5.1,

3 The external unit identified by a particular value of a scalar-int-expr is the same external unit in all program units of the program.

where they provide this sample code in note 9.14:

In the example:

SUBROUTINE A
   READ (6) X
      ...
SUBROUTINE B
   N = 6
   REWIND N

the value 6 used in both program units identifies the same external unit.

Upvotes: 1

Alexander Vogt
Alexander Vogt

Reputation: 18098

Yes, that is possible (for both reading and writing). Here is a short example:

module test_mod
contains

  subroutine myWrite( uFile )
    implicit none
    integer, intent(in) :: uFile

    write(uFile, *) 'Hello world'
  end subroutine
end module

program test
  use test_mod
  implicit none
  integer :: uFile, stat

  open(newunit=uFile, file='test.txt', status='replace', &
       action='write', iostat=stat)
  if(stat.ne.0) return

  call myWrite( uFile )
  close (uFile)
end program

$ cat test.txt 
 Hello world

Upvotes: 1

Related Questions