The Queen's University of Belfast
Parallel Computer Centre

[Next] [Previous] [Top]

9 File-based Input and Output

In the previous modules all input and output was performed to the default devices namely the screen and the keyboard. In many circumstances this is not the most appropriate action, i.e. temporary storage of large amounts of intermediate results; large amounts of input or output; output from one program used as the input of another; a set of input data which is used many times.

A mechanism is required which permits a programmer to direct input to be performed on data from a source other than the keyboard (during execution time) and to store output in a more "permanent" and capacious form. This is generally achieved by utilizing the computer's filestore which is a managed collection of files. A file such as the source program or a set of I/O data is normally formatted, which means it consists of an ordered set of character strings separated by an end of record marker. A formatted file may be viewed using an editor or printed on a printer. An unformatted file (see later) has no discernable structure and should be regarded as single stream of bytes of raw data. An unformatted file is normally only viewed using a suitable user written program.

9.1 Unit Numbers

Fortran I/O statements access files via a unique numeric code or unit number. Each unit number specifies a data channel which may be connected to a particular file or device. The program may set up a connection specifically, or use the defaults, and may at any time break and redefine the connection. These numbers must lie in the range 1..99.

Unit numbers may be specified as:

A statement such as a READ, WRITE or OPEN is directed to use a particular unit by specifying the UNIT keyword as follows: UNIT=10 or UNIT=NUNIT. The unit number may also be specified as a positional argument as shown later.

Some computer systems have a naming convention which will "map" unit numbers to default file names, for example when using unit number 10 on a VAX/VMS system this will map to a file called FOR010.DAT and on a Unix to a file called fort.10.

Also some computer systems provide a form of external variable which may be defined prior to execution and the contents of the variable used as a filename. Again on a VAX/VMS system accessing unit 10 will cause an external variable FOR010 to be checked for a filename.

System specific information such as this is provided in the language reference manual on most systems.

9.2 READ and WRITE Statements

9.2.1 READ Statement

There are two forms of the READ statement, which correspond to the PRINT and WRITE output statements covered later.

READ format-spec,I/O list !This form is not used in this course


READ (clist) [I/O list]

where clist is defined as

[UNIT=] unit-number,

[FMT=] format-spec

[,REC= record-number]







For example:



READ 100, I

READ (*,*) A,B,C


READ (5,100) X, Y, Z

READ (UNIT=10,FMT=100,ERR=10,IOSTAT=ios)

The unit number and format-specifier must be supplied and in the correct order but the other items are optional. In the last example, if an error occurrs, control passes to the statement labelled 10 and the variable specified as ios will return a positive, system dependent integer. The value 0 will be returned if the operation completes successfully.

9.2.2 WRITE Statement

There are two output statements: the PRINT and the WRITE statement. Only the WRITE statement is covered in this course as the PRINT statement is simply a limited form of the WRITE statement. The WRITE statement may be list-directed or format-directed and has the general form:

WRITE (clist) [I/O list]

where clist is defined as

[UNIT=] unit-number,

[FMT=] format-spec

[,REC= record-number]






For example:

WRITE (*,*)

WRITE (6,*) I,J

WRITE (6,100) I


WRITE (UNIT=file1,FMT=100,REC=recordnumber, ERR=10) newline

9.3 OPEN Statement

The OPEN statement is used to connect a unit number to a file specifying certain properties for that file which differ from the defaults. It can be used to create or connect to an existing file. In addition to the standard form described some compliers may provide a number of non-standard additional keywords. Common programming practice places all OPEN statements in a subroutine which is called in the initialization phase of the main program. OPEN statements invariably contain system specific file names and non-standard features thus, should the program be required to run on more than one computer system, the OPEN statements may be easily located.

The OPEN statement has the general form:

OPEN (u, [olist] )


u is a valid unit number specifier (with or without the keyword)

olist is a list of keyword clauses:

keyword "=" value {"," keyword "=" value}

For example:




The following keywords are specified in the Fortran 90 language standard:


where filename is a valid filename for the particular system. Note that case sensitivity is system specific. e.g. FILE='output.test'


where st may be 'OLD', 'NEW', 'REPLACE', 'SCRATCH' or 'UNKNOWN'. If 'OLD' is specified the file must exist; if 'NEW' the file must not exist; if 'REPLACE' and the file exists it will be deleted before a new file is created; and if 'SCRATCH' the file will be deleted when closed. In general use 'OLD' for input and 'NEW' for output.


GOTO label if an error occurs opening the file.


where ios is an integer variable which is set to zero if the statement is executed successfully or to an implementation dependent constant otherwise.


where fm may be 'FORMATTED' or 'UNFORMATTED', the default is 'FORMATTED' for sequential files and 'UNFORMATTED' for direct access files.


where acc may be 'SEQUENTIAL' or 'DIRECT'


where rl is the maximum record length (positive integer) for a direct access file. For formatted files this is the number of characters and for unformatted it is usually the number of bytes or words (system dependent).


where bl is either 'NULL' or 'ZERO' and determines how blanks in a numeric field are interpreted.


where pos may be 'ASIS', 'REWIND' or 'APPEND' which are interpreted as positioning the file at the position it was previously accessed, positioning the file at the start; and positioning the file after the previously end of the file. Defaults to ASIS.


where pad may be 'YES' or 'NO'. If 'YES' formatted input is padded out with blank characters; if 'NO' the length of the input record should not be exceeded.


where del may be 'APOSTROPHE' or 'QUOTE' or 'NONE' indicating which character used when delimiting character expressions in list-directed or NAMELIST output. Defaults to 'NONE'.


where act may be 'READ', 'WRITE' or 'READWRITE' specifying the permitted modes of operation on the file. Default is processor dependent.

For example:

OPEN (UNIT=10,FILE='fibonacci.out')

OPEN (UNIT=11,FILE='fibonacci.out',STATUS='NEW',ERR=10)



WRITE(6,*) 'Error opening file: fibonacci.out.'

OPEN (UNIT=12, FILE='student.records', STATUS='OLD', &






WRITE (6,*) &

'Error opening file: student.records.'

WRITE (6,*) 'IOS = ',IOS



If you are in any doubt about the default values for any of the fields of the OPEN statement, especially as some are machine dependent, specify the required values. The combinations of possible error conditions, mean that careful thought should be given to the specification of OPEN statements and the associated error statements. Specifying some values alter the default values of others and some specifies are mutually exclusive, i.e. only one or the other but not both, for example RECL and ACCESS='SEQUENTIAL' may not be used together.

9.4 CLOSE statement

This statement permits the orderly disconnection of a file from a unit either at the completion of the program, or so that a connection may be made to a different file or to alter a property of the file. The CLOSE statement has the general form

CLOSE ([UNIT=]u [,IOSTAT=ios] [,ERR=label] [,STATUS=st])

where st can be 'KEEP' or 'DELETE'. The value 'KEEP' cannot be applied to a file opened as 'SCRATCH'.

For example:

CLOSE (10)



9.5 INQUIRE statement

This statement may be used to check the status of a file or the connection to a file. It causes values to be assigned to the variables specified in the inquiry-list which indicate the status of the file with respect to the specified keywords. The INQUIRE statement has the general form:

INQUIRE (inquiry-list)

where inquiry-list may be either




plus any combination of the (possible return values are given as a comment)

EXIST=lex ! true or false

OPENED=lod ! true or false

NUMBER=unum ! unit number

NAME=fnm ! filename



DIRECT=dir ! 'YES' or 'NO'

FORMATTED=fmt ! 'YES' or 'NO'

UNFORMATTED=unfmt ! 'YES' or 'NO'


NEXTREC=recn ! number of next record for direct access files only

RECL=recl ! record length for direct access files only

Note that recl, recn and unum and integer variables.

9.6 Direct Access Files

A direct access file is a random access table-like structure which may be inspected or amended. Such a file may be created and accessed using the RECL and ACCESS='DIRECT' keywords on the OPEN statement and REC on the relevant READ and WRITE statements as follows:



RECL=200, ACCESS='DIRECT', ......)



The ERR and IOSTAT keywords should be used to handle possible error conditions such as reading beyond the end of file. One limitation on a direct access file is that all the records must be of fixed length. On some computer systems a direct access file may not be created by a program but must be created using system commands prior to program execution. Also on some systems such a file may not be extended by the program but must also have a known fixed number of records.

9.7 Exercises

  1. Complete the following statement, which would open an unformatted direct access file with a record length of 100 bytes


  2. Write a section of code which would open 10 files on the unit numbers from 20 to 29. The default values should be used for all keywords.

  3. Write sections of code to perform the following

    (a) test for the existence of a file called TEMP.DAT

    (b) test if a file has been opened on unit 10

    (c) test to see if the file opened on unit 15 is a direct access file and if so what the record length is.

    The program fragments should output the results in a suitable form.

  4. Write a Fortran program which will prompt the user for a file name, open that file and then read the file line by line outputting each line to the screen prefixed with a line number. Use the file which contains the source of the program as a test file.

  5. Write a Fortran program which will create a temporary direct access file, prompt for the name of an existing file and read that file sequentially writing each line to the next record of the temporary direct access file. The program should then repeatedly prompt the user for a number representing the number of a line in the input file and display that line on the screen. The program should halt when the number 0 is entered. The program should handle all possible error conditions such as the file does not exist or a line number out of range is specified and inform the user accordingly.

[Next] [Previous] [Top]
All documents are the responsibility of, and copyright, © their authors and do not represent the views of The Parallel Computer Centre, nor of The Queen's University of Belfast.
Maintained by Alan Rea, email
Generated with CERN WebMaker