Skip to content
Tutorials Center
My learning

Topics

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

Namelists, Stream Access and Unformatted Files

Read configuration with Fortran namelists, write fast unformatted binary files, use direct and stream access, and exchange data safely between programs.

Text files with formats (file I/O basics) are readable but slow and lossy: printing a real as f8.3 throws digits away. This lesson covers three more tools. Namelists make configuration files effortless, unformatted files store numbers exactly as in memory, and direct and stream access let you jump around a file instead of reading it from the top.

Namelist input: configuration without parsing

A namelist names a group of variables so one statement reads or writes all of them. You declare the group, and the input file assigns by name:

FORTRAN
program simulate
  implicit none
  integer :: steps = 100
  real    :: dt = 0.01
  character(len=20) :: method = "euler"
  logical :: verbose = .false.
  integer :: u, ios

  namelist /params/ steps, dt, method, verbose

  open (newunit=u, file="params.nml", status="old", action="read", iostat=ios)
  if (ios == 0) then
    read (u, nml=params)
    close (u)
  end if

  print *, "steps =", steps
  print *, "dt    =", dt
  print *, "method= ", trim(method)
end program simulate

The input file params.nml looks like this:

TEXT
&params
  steps   = 500
  dt      = 0.002
  method  = "rk4"
  verbose = .true.
/

Rules worth knowing:

  • The group starts with &name and ends with / (older code uses $end).
  • Variables not mentioned keep their current values, so defaults set in the program survive. That is why the declarations above carry initial values.
  • Order does not matter, and you may comment lines with ! in most compilers.
  • Arrays are given as a = 1.0, 2.0, 3.0, or by element, a(3) = 7.0.
  • Names in the file that are not in the namelist cause a runtime error: a typo is caught rather than ignored.

Writing is symmetric: write (u, nml=params) outputs the group in a format that read accepts, which makes it perfect for saving the settings of a run next to its results.

Python Stand-in: defaults overridden by a settings block

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.

Unformatted (binary) files

Add form="unformatted" and values are copied to disk exactly as stored in memory, with no conversion to text:

FORTRAN
real(8) :: field(1000)
integer :: u

open (newunit=u, file="field.bin", form="unformatted", &
      access="sequential", status="replace", action="write")
write (u) field
close (u)

open (newunit=u, file="field.bin", form="unformatted", &
      status="old", action="read")
read (u) field
close (u)

Advantages: no rounding (the numbers return bit for bit), much smaller files and much faster I/O than formatted text. For large simulation output, this is usually the right choice.

Costs: you cannot read the file in an editor, and the layout depends on the compiler. A sequential unformatted file contains record markers (a length before and after each write), whose size and byte order differ between compilers and machines. A file written by one compiler may not be readable by another. Within one toolchain on one machine it is reliable.

Stream access: a plain byte stream

access="stream" removes record markers entirely. The file is just bytes, and you can set the position with pos= (1-based):

FORTRAN
integer :: u
real(8) :: x(5) = [1d0, 2d0, 3d0, 4d0, 5d0]
real(8) :: y

open (newunit=u, file="data.bin", access="stream", form="unformatted", &
      status="replace", action="readwrite")
write (u) x                  ! 40 bytes, nothing else
read (u, pos=17) y           ! element 3: bytes 17-24
close (u)
print *, y                   ! 3.0

Because no markers are added, a stream file matches the layout other languages expect (for example NumPy's fromfile, or a C fread), as long as the byte order agrees. Stream access is the portable way to read and write raw binary data. You can also use form="formatted", access="stream" to read a text file byte by byte with no record structure, including newlines in the data.

The tool for bytes is inquire (unit=u, size=n), and inquire (unit=u, pos=p) reports the current position.

Direct access: fixed-size records

With access="direct" every record has the same length (recl=) and you read record number rec=n directly:

FORTRAN
open (newunit=u, file="table.dat", access="direct", recl=16, &
      form="unformatted", status="replace", action="readwrite")
write (u, rec=3) 3.5d0, 4.5d0     ! 16 bytes = one record
read  (u, rec=3) a, b

recl is measured in bytes for unformatted files with most compilers but in processor-dependent units for some, so check your compiler's documentation. For new code, stream access with pos= offers the same random access with fewer surprises.

flowchart TD
    A["Which file type?"] --> B["People will read it"]
    A --> C["Program-to-program data"]
    B --> D["formatted text<br/>or namelist for settings"]
    C --> E["same toolchain, simple"]
    C --> F["other languages / long-term"]
    E --> G["sequential unformatted"]
    F --> H["stream unformatted<br/>fixed kind and byte order"]

Choose the format from who reads the file next.

Endianness and kinds

Binary files record raw bytes, so the kind (real(4) vs real(8)) and the byte order must match between writer and reader. gfortran offers convert="big_endian" or convert="little_endian" in open to read files written on another machine type. Always document the kind (real(8), 8 bytes, little-endian) beside the file format.

Python Stand-in: exact bytes with a stream file

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

  • Misspelling a namelist variable: the read fails. Keep the file and the namelist statement in sync.
  • Reading an unformatted file with a different kind than it was written with.
  • Mixing form="formatted" and "unformatted" on the same file.
  • Trusting sequential unformatted files across compilers.
  • Using recl with the wrong unit, giving truncated records.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to variables absent from the namelist input?

    Only the listed names are assigned, so program defaults survive.
  2. 2. Why use unformatted files for large results?

    Binary I/O avoids text conversion and keeps exact bit patterns.
  3. 3. What does access='stream' remove compared with sequential unformatted?

    A stream file is plain bytes, so layout is predictable and other languages can read it.
  4. 4. Which keyword sets the byte position in a stream read?

    pos= (1-based) selects the byte position in stream access; rec= is for direct access.

Summary

  • Namelists read and write named groups of variables; unlisted ones keep their values.
  • Unformatted files store exact binary data: fast and small, but kind and byte order matter.
  • Stream access gives raw bytes with pos= and portable layout; direct access uses fixed-length records.
  • Pick the file type by who reads it next.

Next: do concurrent and elemental operations