Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท File I/O and Formatting

Reading and Writing Files in Fortran

Work with files in Fortran: open and close units, newunit, status and action, read until end of file with iostat, check errors, rewind, inquire and use scratch files.

Fortran talks to files through units: integer handles you attach to a file with open, use in read and write, and release with close. The same read and write statements you use for the keyboard and screen (units *, or input_unit and output_unit from iso_fortran_env) work on files, so formatting rules from formatted output apply unchanged.

The Fortran compiler and a file system are not available in the browser, so the Fortran listings here are read-only. The Python stand-ins use an in-memory file to show the same flow.

Open, write, close

FORTRAN
program write_file
  implicit none
  integer :: u, i

  open (newunit=u, file="squares.txt", status="replace", action="write")
  do i = 1, 5
    write (u, "(i3, i6)") i, i**2
  end do
  close (u)
end program write_file

newunit=u asks the runtime to choose a free unit number and store it in u. Older code picked a number by hand (open (unit=10, ...)), which risks clashing with another part of the program, so prefer newunit.

Important open specifiers:

Specifier Values Meaning
file= string file name
status= "old", "new", "replace", "scratch", "unknown" must exist / must not exist / overwrite / temporary / either
action= "read", "write", "readwrite" what you will do; protects against mistakes
position= "asis", "rewind", "append" where to start; "append" adds to the end
form= "formatted" (default), "unformatted" text or raw binary records
iostat= / iomsg= integer / string error code and message instead of crashing

Reading, and detecting the end

FORTRAN
program read_file
  implicit none
  integer :: u, ios, n, sq
  integer :: total = 0
  character(len=80) :: msg

  open (newunit=u, file="squares.txt", status="old", action="read", &
        iostat=ios, iomsg=msg)
  if (ios /= 0) then
    print *, "Cannot open file: ", trim(msg)
    stop 1
  end if

  do
    read (u, *, iostat=ios) n, sq
    if (ios /= 0) exit          ! end of file or error
    total = total + sq
  end do

  close (u)
  print *, "Sum of squares:", total
end program read_file

If iostat= is present, a failed read does not crash the program. Instead ios is set: zero for success, negative for end of file or end of record, positive for an error (bad number, file problem). The iostat_end constant from iso_fortran_env is the specific end-of-file value:

FORTRAN
use, intrinsic :: iso_fortran_env, only: iostat_end
...
if (ios == iostat_end) exit

Distinguishing the two matters: end of file is normal, anything positive deserves an error message with iomsg.

Python Stand-in: write a file, then read until the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading whole lines and fields

read (u, *) splits input on blanks or commas (list-directed). For fixed-format files give a format, and to read a whole line as text use (a):

FORTRAN
character(len=200) :: line
read (u, "(a)", iostat=ios) line

A line longer than the variable is truncated, shorter lines are blank-padded, so use trim(line) when you use it. Read the first line as text, then parse parts of it with an internal read (read (line, *) x, y).

Free-form numbers sometimes need size or non-advancing input to read variable-length lines. A simple, robust pattern is: read the line into a long character, then parse it.

Positioning: rewind, backspace, append

FORTRAN
rewind (u)          ! go back to the start
backspace (u)       ! step back one record
open (newunit=v, file="log.txt", position="append", action="write", &
      status="unknown")

rewind is how you read a file twice (once to count lines, once to fill an array sized from the count). With status="scratch" the runtime creates a temporary file that disappears at close: no name needed.

Does the file exist? inquire

FORTRAN
logical :: exists
inquire (file="data.csv", exist=exists)
if (.not. exists) print *, "data.csv missing"

inquire also reports size (size=), whether a unit is open (opened=), and the name attached to a unit.

Standard units

iso_fortran_env provides input_unit, output_unit and error_unit. Send diagnostics to the error stream so they stay out of redirected results:

FORTRAN
use, intrinsic :: iso_fortran_env, only: error_unit
write (error_unit, "(a)") "warning: negative input ignored"

A worked example: average of the numbers in a file

FORTRAN
program average
  implicit none
  integer :: u, ios, n
  real :: x, total

  open (newunit=u, file="values.txt", status="old", action="read", iostat=ios)
  if (ios /= 0) stop "values.txt not found"

  n = 0
  total = 0.0
  do
    read (u, *, iostat=ios) x
    if (ios /= 0) exit
    n = n + 1
    total = total + x
  end do
  close (u)

  if (n > 0) then
    print "(a, f8.3)", "Mean = ", total / n
  else
    print *, "No data"
  end if
end program average
Python Stand-in: average of numbers from text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Forgetting close. Data may stay unflushed in a buffer (the runtime closes open units at normal program end, but not after a crash).
  • Opening with status="new" on an existing file: error. Use "replace" to overwrite.
  • Not testing iostat on open: the program stops with a cryptic runtime message.
  • Treating every non-zero iostat as end of file; positive values are real errors.
  • Assuming the working directory: a relative file name is relative to where the program runs, not where the source lives.
  • Reusing hard-coded unit numbers; use newunit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does newunit=u do in open?

    newunit avoids hand-picked unit numbers that could clash.
  2. 2. What is a negative iostat value after read?

    Zero is success, negative signals end of file/record, positive signals an error.
  3. 3. Which status makes the open fail if the file does not exist?

    old requires an existing file. new requires it not to exist, replace overwrites.
  4. 4. How do you read the file a second time?

    rewind repositions to the first record.

Summary

  • Attach units with open (newunit=u, file=..., status=..., action=...); release with close.
  • Use iostat= and iomsg= to handle errors; zero is success, negative is end of file, positive is an error.
  • Read lines with (a) and parse with an internal read; reposition with rewind, backspace and position="append".
  • inquire checks for a file; error_unit carries diagnostics.

Next: Namelists, stream access and unformatted files