TExcelTAD
Home › Fortran › Fortran Internal & Scratch-File I/O

Fortran Internal & Scratch-File I/O

Fortran's I/O statements (open, read, write, close) work with units: numbered channels attached to files. The same statements also work with internal files (character variables), which are the standard way to convert between numbers and text. The playground can't access your disk, so this lesson uses internal files and scratch files, temporary files that the system deletes when they are closed. Everything shown works the same with real files.

Internal files: writing into a string

A write whose unit is a character variable formats the values into that string:

fortran · try it yourself
program internal_write
  implicit none
  character(len=40) :: line
  character(len=16) :: filename
  integer :: step

  write(line, '(a, f8.3, a)') 'Energy = ', 1.5e-2 * 1000, ' J'
  print '(a)', trim(line)

  do step = 1, 3
    write(filename, '(a, i4.4, a)') 'frame_', step * 50, '.dat'
    print '(a)', trim(filename)
  end do
end program internal_write
Energy =   15.000 J
frame_0050.dat
frame_0100.dat
frame_0150.dat

Generating numbered file names with i4.4 (zero-padded to 4 digits) is a very common use.

Internal files: reading from a string

read from a character variable parses text. List-directed reading (*) splits the input on blanks or commas:

fortran · try it yourself
program internal_read
  implicit none
  character(len=60) :: record
  character(len=10) :: station
  real :: temp, pressure
  integer :: year, ios

  record = 'OSLO  2024  -3.5  1012.8'
  read(record, *) station, year, temp, pressure
  print '(a, a, i0, a, f5.1, a, f7.1)', trim(station), ' (', year, '): T = ', temp, ', p = ', pressure

  record = '12, 7, 2025'
  read(record, *) year, temp, pressure          ! commas work as separators too
  print '(i0, 2f8.1)', year, temp, pressure

  record = 'not-a-number'
  read(record, *, iostat=ios) temp
  if (ios /= 0) print '(a, i0)', 'could not parse, iostat = ', ios
end program internal_read
OSLO (2024): T =  -3.5, p =  1012.8
12     7.0  2025.0
could not parse, iostat = 5010

Notice that read(record, *) converts each item to the type of its variable: 12 went into the integer year, while 7 and 2025 were read into the reals temp and pressure without complaint. The exact iostat value of a failed read is compiler-specific: only "zero means success, negative means end of file, positive means error" is guaranteed.

Opening a scratch file

open(newunit=u, ...) lets the runtime choose a free unit number and stores it in u; never hard-code numbers like 10 in new code. status='scratch' creates an anonymous temporary file:

fortran · try it yourself
program scratch_demo
  implicit none
  integer :: u, i, n
  real :: x, total

  open(newunit=u, status='scratch', action='readwrite', form='formatted')

  do i = 1, 5
    write(u, '(i3, f8.2)') i, i * 1.25
  end do

  rewind(u)                     ! go back to the start before reading
  total = 0.0
  do i = 1, 5
    read(u, *) n, x
    total = total + x
  end do
  close(u)                      ! scratch files are deleted on close

  print '(a, f8.2)', 'sum of column 2: ', total
end program scratch_demo
sum of column 2:    18.75

For a real file you would write open(newunit=u, file='results.txt', status='replace', action='write'). The common status values are 'old' (must exist), 'new' (must not exist), 'replace' (create or overwrite) and 'scratch'.

Reading until end of file

Usually you don't know how many lines a file has. Read in an endless loop and stop when iostat reports end of file, which is the negative constant iostat_end from iso_fortran_env:

fortran · try it yourself
program read_to_eof
  use iso_fortran_env, only: iostat_end
  implicit none
  integer :: u, ios, count
  character(len=80) :: line

  open(newunit=u, status='scratch', action='readwrite')
  write(u, '(a)') '# planet  moons'
  write(u, '(a)') 'Earth 1'
  write(u, '(a)') 'Mars 2'
  write(u, '(a)') 'Jupiter 95'
  rewind(u)

  count = 0
  do
    read(u, '(a)', iostat=ios) line
    if (ios == iostat_end) exit
    if (ios /= 0) error stop 'read error'
    if (line(1:1) == '#') cycle             ! skip comment lines
    count = count + 1
    print '(i0, a, a)', count, ': ', trim(line)
  end do
  close(u)
  print '(a, i0, a)', 'read ', count, ' data lines'
end program read_to_eof
1: Earth 1
2: Mars 2
3: Jupiter 95
read 3 data lines

Reading each line into a string first (format '(a)') and then parsing it with an internal read is a robust pattern: you can skip comments, report the bad line, and handle varying formats.

Unformatted (binary) files

Formatted files store text. Unformatted files store the raw bytes of the values: they are smaller, much faster, and lossless for reals, but not human-readable or necessarily portable between compilers. access='stream' gives a plain byte stream, like C's fwrite:

fortran · try it yourself
program binary_io
  use iso_fortran_env, only: real64
  implicit none
  integer :: u, i, file_bytes
  real(real64) :: original(4), restored(4)

  original = [(sqrt(real(i, real64)), i = 1, 4)]
  open(newunit=u, status='scratch', form='unformatted', access='stream')
  write(u) original
  inquire(unit=u, size=file_bytes)
  rewind(u)
  read(u) restored
  close(u)

  print '(a, i0)', 'bytes in file: ', file_bytes
  print '(a, l1)', 'identical after round trip: ', all(original == restored)
end program binary_io
bytes in file: 32
identical after round trip: T

Four 8-byte reals take exactly 32 bytes. inquire can ask many questions about a unit or file: its size, whether it exists (inquire(file='x.dat', exist=found)), whether it's open, and more.

Test yourself

What does write(buf, '(i0)') n do when buf is a character variable?

  1. Writes n to a file named buf
  2. Formats n as text into the string buf
  3. Reads n from buf
  4. Is a compile error

Why use open(newunit=u, ...) instead of open(10, ...)?

  1. Unit 10 is reserved
  2. The runtime picks a free unit number, avoiding clashes with other code
  3. newunit is faster
  4. Numbered units are deprecated syntax errors

How do you detect end of file while reading?

  1. Check eof(u)
  2. Use iostat=ios and compare ios with iostat_end
  3. Catch an exception
  4. Read until a blank line