Sun Studio 12: Fortran Programming Guide

2.2 Direct I/O

Direct or random I/O allows you to access a file directly by record number. Record numbers are assigned when a record is written. Unlike sequential I/O, direct I/O records can be read and written in any order. However, in a direct access file, all records must be the same fixed length. Direct access files are declared with the ACCESS=’DIRECT’ specifier on the OPEN statement for the file.

A logical record in a direct access file is a string of bytes of a length specified by the OPEN statement’s RECL= specifier. READ and WRITE statements must not specify logical records larger than the defined record size. (Record sizes are specified in bytes.) Shorter records are allowed. Unformatted, direct writes leave the unfilled part of the record undefined. Formatted, direct writes cause the unfilled record to be padded with blanks.

Direct access READ and WRITE statements have an extra argument, REC=n, to specify the record number to be read or written.

Example: Direct access, unformatted:


      OPEN( 2, FILE=’data.db’, ACCESS=’DIRECT’, RECL=200,
&             FORM=’UNFORMATTED’, ERR=90 )
      READ( 2, REC=13, ERR=30 ) X, Y

This program opens a file for direct access, unformatted I/O, with a fixed record length of 200 bytes, then reads the thirteenth record into X and Y.

Example: Direct access, formatted:


      OPEN( 2, FILE=’inven.db’, ACCESS=’DIRECT’, RECL=200,
&             FORM=’FORMATTED’, ERR=90 )
      READ( 2, FMT=’(I10,F10.3)’, REC=13, ERR=30 ) X, Y

This program opens a file for direct access, formatted I/O, with a fixed record length of 200 bytes. It then reads the thirteenth record and converts it with the format (I10,F10.3).

For formatted files, the size of the record written is determined by the FORMAT statement. In the preceding example, the FORMAT statement defines a record of 20 characters or bytes. More than one record can be written by a single formatted write if the amount of data on the list is larger than the record size specified in the FORMAT statement. In such a case, each subsequent record is given successive record numbers.

Example: Direct access, formatted, multiple record write:


      OPEN( 21, ACCESS=’DIRECT’, RECL=200, FORM=’FORMATTED’)
      WRITE(21,’(10F10.3)’,REC=11) (X(J),J=1,100)

The write to direct access unit 21 creates 10 records of 10 elements each (since the format specifies 10 elements per record) these records are numbered 11 through 20.