HP Fortran Programmer's Reference (September 2007)

I/O and file handling
Connecting a file to a unit
Chapter 8206
Connecting a file to a unit
Before a program can perform any I/O operations on an external file, it must establish a
logical connection between the file and a unit number. Once the connection is established, the
program can reference the file by specifying the associated unit number (a nonnegative
integer expression). In the following example, the OPEN statement connects unit number 1 to
the file my_data, allowing the WRITE statement to write the values in total_acct and
balance to my_data:
OPEN (UNIT=1, FILE='my_data')
WRITE (1, '(F8.2)') total_acct, balance
The following sections describe three types of unit numbers:
Those that are explicitly connected by means of the OPEN statement
Preconnected unit numbers
Automatically opened unit numbers
Connecting to an external file
Typically, the connection between an external file and a unit number is established by the
OPEN statement. When the program is finished using the file, the connection is terminated by
the CLOSE statement. Once the connection is terminated, the unit number can be assigned to a
different file by means of another OPEN statement. Similarly, a file whose connection was
broken by a CLOSE statement can be reconnected to the same unit number or to a different
unit number.
A unit cannot be connected to more than one file at a time.
The following code establishes a connection between unit 9 and the external file first_file,
which is to be by default opened for sequential access. When the program is finished with the
file, the CLOSE statement terminates the connection, making the unit number available for
connection to other files. Following the CLOSE statement, the program connects unit 9 to a
different external file, new_file:
! connect unit 9 to first_file
OPEN (9, FILE='first_file')
...
! process file
...
! terminate connection
CLOSE (9)
! connect same unit number to new_file