Next we'd like to try reading from, and writing to, a file. As mentioned before, the channels for standard error/input/output are automatically opened for us. But disk files have to be opened before they can be written to, or read from. Here, we will cover only the most basic file open/close operations.

The open statement contains a unit number and a file name. Opening a file connects the file handle, i.e., the unit number, to the actual file. Later, when reading from the file, the unit number can be used to specify the file. Unit numbers are integers between 0 and 255. Bear in mind that 0, 5, and 6 are already assigned to standard error/input/output. After closing a file, the unit number is available for re-use.

Example: Writing to a file. In this example the filename is a literal constant.

Example: Writing to a file. In this example the filename is a character string.

Reading from a file is similar:

One line of an input file would look like this:

Note that the integer does not have to be right justified within its field to be read correctly.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement