A scratch file is a unit with no name that is opened and discarded automatically. Useful for short-lived buffers.

Program

Play the program to write a number to a scratch unit, rewind, read it back, and double it.

file_io.f90
Replay: real traced execution (multi-file project)
program file_io_demo
    implicit none
    integer :: unit_, value_in, value_out
    value_in = 42
    open(newunit=unit_, status='scratch', action='readwrite')
    write(unit_, '(I0)') value_in
    rewind(unit_)
    read(unit_, *) value_out
    close(unit_)
    print '(I0)', value_out * 2
end program file_io_demo
  1. value_in ← 42

    3integer :: unit_, value_in, value_out4value_in = 425open(newunit=unit_, status='scratch', action='readwrite')
    values this step42value_in
  2. scratch unit ← opened

    4value_in = 425open(newunit=unit_, status='scratch', action='readwrite')6write(unit_, '(I0)') value_in
    values this stepopenedscratch unit
  3. file ← 42

    5open(newunit=unit_, status='scratch', action='readwrite')6write(unit_, '(I0)') value_in7rewind(unit_)
    values this step42file42value_in
  4. position ← start

    6write(unit_, '(I0)') value_in7rewind(unit_)8read(unit_, *) value_out
    values this stepstartposition
  5. value_out ← 42

    7rewind(unit_)8read(unit_, *) value_out9close(unit_)
    values this step42value_out42file
  6. scratch unit ← closed

    8read(unit_, *) value_out9close(unit_)10print '(I0)', value_out * 2
    values this stepclosedscratch unit
  7. print '(I0)', value_out * 2

    9    close(unit_)10    print '(I0)', value_out * 211end program file_io_demo
    output84
    values this step42value_out

Follow the Scratch File

  1. value_in starts as 42.
  2. The scratch unit opens for reading and writing.
  3. The program writes 42 into the scratch file.
  4. rewind moves back to the start before reading.
  5. value_out is 42, so value_out * 2 prints 84. | step | value | | --- | --- | | write to scratch file | 42 | | after rewind and read | 42 | | doubled output | 84 |
scratch `status='scratch'` opens a temporary unit deleted on close.
newunit `newunit=unit_` picks an unused unit number.
rewind `rewind` returns the file position to the start before reading.

Exercise: file_io.f90

Reproduce 84, then trace how value_in 42 is written, read back as value_out 42, and doubled.