02.07.2013 Views

HP Fortran Programmer's Reference

HP Fortran Programmer's Reference

HP Fortran Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

I/O and file handling<br />

Connecting a file to a unit<br />

Connecting a file to a unit<br />

Before a program can perform any I/O operations on an external file, it must establish a<br />

logical connection between the file and a unit number. Once the connection is established, the<br />

program can reference the file by specifying the associated unit number (a nonnegative<br />

integer expression). In the following example, the OPEN statement connects unit number 1 to<br />

the file my_data, allowing the WRITE statement to write the values in total_acct and<br />

balance to my_data:<br />

OPEN (UNIT=1, FILE='my_data')<br />

WRITE (1, '(F8.2)') total_acct, balance<br />

The following sections describe three types of unit numbers:<br />

174<br />

Those that are explicitly connected by means of the OPEN statement<br />

Preconnected unit numbers<br />

Automatically opened unit numbers<br />

Connecting to an external file<br />

Typically, the connection between an external file and a unit number is established by the<br />

OPEN statement. When the program is finished using the file, the connection is terminated by<br />

the CLOSE statement. Once the connection is terminated, the unit number can be assigned to a<br />

different file by means of another OPEN statement. Similarly, a file whose connection was<br />

broken by a CLOSE statement can be reconnected to the same unit number or to a different<br />

unit number.<br />

A unit cannot be connected to more than one file at a time.<br />

The following code establishes a connection between unit 9 and the external file first_file,<br />

which is to be by default opened for sequential access. When the program is finished with the<br />

file, the CLOSE statement terminates the connection, making the unit number available for<br />

connection to other files. Following the CLOSE statement, the program connects unit 9 to a<br />

different external file, new_file:<br />

! connect unit 9 to first_file<br />

OPEN (9, FILE='first_file')<br />

...<br />

! process file<br />

...<br />

! terminate connection<br />

CLOSE (9)<br />

! connect same unit number to new_file<br />

Chapter 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!