next up previous contents index
Next: Records Up: Input/Output Facilities Previous: Input/Output Facilities

Files, I/O Units, and Records

In Fortran the term file   is used for anything that can be handled with a READ or WRITE statement: the term covers not just data files stored on disc or tape and also peripheral devices such as printers or terminals. Strictly these should all be called external files, to distinguish them from internal files.

    An internal file is nothing more than a character variable or array which is used as a temporary file while the program is running. Internal files can be used with READ and WRITE statements in order to process character information under the control of a format specification. They cannot be used by other I/O statements.

Before an external file   can be used it must be connected to an I/O unit. I/O units are integers which may be chosen freely from zero up to a system-dependent limit (usually at least 99). Except in OPEN and INQUIRE statements, files can only be referred to via their unit numbers.

  The OPEN statement connects a named file to a numbered unit. It usually specifies whether the file already exists or whether a new one is to be created, for example:

 
      OPEN(UNIT=1, FILE='B:INPUT.DAT', STATUS='OLD') 
      OPEN(UNIT=9, FILE='PRINTOUT', STATUS='NEW')
For simplicity most of the examples in this section show an actual integer as the unit identifier, but it helps to make software more modular and adaptable if a named constant or a variable is used instead.

  I/O units are a global resource. A file can be opened in any program unit; once it is open I/O operations can be performed on it in any program unit provided that the same unit number is used. The unit number can be held in an integer variable and passed to the procedure as an argument.

The connection between a file and a unit, once established, persists until:

Although all files are closed when the program exits, it is good practice to close them explicitly as soon as I/O operations on them are completed. If the program terminates abnormally, for example because an error occurs or it is aborted by the user, any files which are open, especially output files, may be left with incomplete or corrupted records.

  The INQUIRE statement can be used to obtain information about the current properties of external files and I/O units. INQUIRE is particularly useful when writing library procedures which may have to run in a variety of different program environments. You can find out, for example, which unit numbers are free for use or whether a particular file exists and if so what its characteristics are.


next up previous contents index
Next: Records Up: Input/Output Facilities Previous: Input/Output Facilities

Mario Storti
Wed Nov 4 19:32:56 ART 1998