Files and unit numbers

Fortran connects a program to a file through a unit number — an integer the program chooses and then uses in every read and write that touches the file. The open statement associates a unit with a file and sets how it will be used; close ends the association. Preconnected units exist for standard input and output, which is why simple programs print without an explicit open.

Formatted and unformatted I/O

Formatted I/O translates between numbers and human-readable text; the program can specify the format or use list-directed formatting (the * in read(10,*) and write(10,*)), which chooses a reasonable layout automatically. Unformatted I/O copies the raw internal representation instead. It is faster and exact — no rounding through decimal text — but the file is not readable as text, and it is best treated as belonging to the program that wrote it.

Checking for errors with iostat

I/O can fail: a file may be missing, or a read may run past the end of the data. The iostat= specifier places a status code into an integer variable — zero means the operation succeeded, a positive value means an error, and a negative value means end-of-file. Checking it keeps one bad file from silently producing wrong results.

A small example

The program below reads numbers from a text file until the end of the file, printing each one:

program read_numbers implicit none integer :: ios real :: x open(unit=10, file='data.txt', status='old', & action='read', iostat=ios) if (ios /= 0) then print *, 'Could not open data.txt' stop end if do read(10, *, iostat=ios) x if (ios /= 0) exit ! error or end of file print *, x end do close(10) end program read_numbers

File handling is the bridge between a program and the data it computes on; the Numerical Methods section builds on it next.