User-defined I/O for a type

print *, p for a record prints something the compiler chose, and read (*, *) p expects exactly the components in order. Defined I/O replaces both: the type carries a procedure that writes it and a procedure that reads it, and every list-directed statement, every formatted write with the dt descriptor and every internal file uses them. This lesson writes both halves for a point and reads the error a wrong signature gives.

Why defined I/O

A derived type without defined I/O is written as its components separated by spaces, which is fine for a quick look and wrong for a file format: the parentheses, the units and the number of decimals are all missing, and a reader of the file has no way to know what the numbers are. Defined I/O lets the type own its text, so print *, p writes point( and the two numbers and a closing parenthesis, and the same text comes back through read.

WRITE(FORMATTED)

The binding is a generic named write with the interface name formatted: generic :: write(formatted) => write together with procedure :: write => write_point. The name write is the one the language reserves for this purpose, and a type may also bind read(formatted) and the unformatted pair, each with its own procedure.

The file dio.f90:

module geom implicit none private public :: point type :: point real :: x = 0.0 real :: y = 0.0 contains procedure :: write => write_point procedure :: read => read_point generic :: write(formatted) => write generic :: read(formatted) => read end type point contains subroutine write_point(dtv, unit, iotype, v_list, iostat, iomsg) class(point), intent(in) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: v_list(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg character(len=20) :: fmt integer :: w w = 7 if (size(v_list) > 0) w = max(7, v_list(1)) write (fmt, '(a,i0,a)') '(a,2f', w, '.2,a)' if (iotype == 'LISTDIRECTED') then write (unit, fmt, iostat=iostat, iomsg=iomsg) 'point(', dtv%x, dtv%y, ')' else write (unit, fmt, iostat=iostat, iomsg=iomsg) '<', dtv%x, dtv%y, '>' end if end subroutine write_point subroutine read_point(dtv, unit, iotype, v_list, iostat, iomsg) class(point), intent(inout) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: v_list(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg if (iotype /= 'LISTDIRECTED' .or. size(v_list) > 0) then iostat = 1 iomsg = 'read_point takes two values and no width' return end if read (unit, *, iostat=iostat, iomsg=iomsg) dtv%x, dtv%y end subroutine read_point end module geom program diodemo use geom implicit none type(point) :: p, q character(len=40) :: buf p = point(1.5, -2.25) print *, p write (*, '(a)', advance='no') 'dt: ' write (*, '(dt(9))') p write (*, '(a)') '' buf = '3.0 4.0' read (buf, *) q print *, q end program diodemo

gfortran -Wall -Wextra -std=f2018 dio.f90 -o dio
./dio

point( 1.50 -2.25)
dt: < 1.50 -2.25>

point( 3.00 4.00)

Three different statements, three different texts, all from the two procedures. The first line is list-directed output and the type answered with its own format. The second is a dt descriptor with the parameter nine, and the type wrote itself between angle brackets in a field of nine. The fourth line came from the internal file: read (buf, *) called read_point, which read two reals out of the string.

The six arguments

Every defined-I/O procedure has the same six dummy arguments, in this order: the data transfer object dtv, the unit, the iotype string, the v_list array, iostat and iomsg. The compiler checks all six, and nothing else may be added except in the unformatted form.

dtv is the value: intent(in) for a write, intent(inout) for a read, and declared with the type itself. unit is the unit number the statement named. iotype is 'LISTDIRECTED' for print and write(*,*), 'DT' for the descriptor, and 'NAMELIST' for a namelist. v_list carries the integers of dt(9), and it is empty for a plain dt.

iostat and iomsg are how the procedure reports a failure: set iostat to a non-zero value and put a message in iomsg. A statement with iostat= then sees the value, and one without it stops the program, which is the same rule as for any other I/O error.

READ(FORMATTED)

read_point reads two reals with list-directed input and refuses anything else, which is the honest thing for a reader that only understands one form. The iotype test is not decoration: a read with the dt descriptor calls the same procedure with 'DT', and a reader that assumed list-directed input would misread the record.

Because the reading procedure is called for every element of an array and for every record of a file, it is the place to validate: a value out of range, a missing field or a unit that does not belong there is reported through iostat once, in one place, instead of in every caller.

The DT edit descriptor

dt is the edit descriptor that means "the type writes itself". With no parameter the v_list is empty and the type decides everything; with dt(9) the type receives nine in v_list(1), and a string form dt'km' passes the text in iotype after the DT prefix. That is how a program asks a type for a particular width or unit without knowing how the type works.

The descriptor is only legal for a derived type with a defined-I/O procedure. For any other type gfortran reports an error at compile time, so a dt in a format string is a promise that the value has one.

A signature gfortran refuses

The six arguments have fixed intents, and a procedure that changes one is refused where the binding is declared:

module geom_bad implicit none type :: point real :: x = 0.0 real :: y = 0.0 contains procedure :: write => write_point generic :: write(formatted) => write end type point contains subroutine write_point(dtv, unit, iotype, v_list, iostat, iomsg) class(point), intent(in) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: v_list(:) integer, intent(inout) :: iostat character(len=*), intent(inout) :: iomsg write (unit, '(a,2f7.2,a)') 'point(', dtv%x, dtv%y, ')' end subroutine write_point end module geom_bad

gfortran -Wall -Wextra -std=f2018 -c badsig.f90

badsig.f90:11:53:

11 | subroutine write_point(dtv, unit, iotype, v_list, iostat, iomsg)
| 1~~~~~
Error: DTIO dummy argument at (1) must have INTENT OUT

The five-character caret sits under iostat and the message names the interface by its standard abbreviation, DTIO. A missing argument is reported in the same place with "Too few dummy arguments in DTIO procedure", and a wrong type for dtv with a message about the passed object.

What defined I/O cannot do

It cannot change the shape of the data: a defined-I/O procedure writes characters to a unit and reads characters from one, so it is not a serialiser for a binary format with a header of its own. It also cannot be used with unformatted transfer unless the type binds the unformatted form, and it does not apply to a namelist unless the type binds that one too.

The one thing to watch is recursion: writing a record whose defined-I/O procedure writes the record again calls itself until the stack ends. Write the components, never the object.

Exercises

  1. Change write_point to print three decimals for the DT form and two for the list-directed one. Which line of the program changes its output?
  2. Write buf = '1.0 2.0 3.0' and read it into a point. What does iostat say, and how would you report it to the caller?
  3. Add dt(4) to the program. What does the output look like, and why?
  4. Remove generic :: write(formatted) and keep the binding. What does print *, p then write?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does generic :: write(formatted) => write bind?

    Answer

    The procedure that writes a value of the type in a formatted context

    write and read are reserved names for defined I/O.

  2. What is the first dummy argument of a defined-I/O procedure?

    Answer

    The data transfer object, declared with the type

    dtv is the value being written or read.

  3. What is iotype for print *, p?

    Answer

    LISTDIRECTED

    List-directed output names itself in iotype.

  4. What does this program print? module m implicit none type :: t integer :: n = 0 contains procedure :: w => tw generic :: write(formatted) => w end type t contains subroutine tw(dtv, unit, iotype, v_list, iostat, iomsg) class(t), intent(in) :: dtv integer, intent(in) :: unit character(len=*), intent(in) :: iotype integer, intent(in) :: v_list(:) integer, intent(out) :: iostat character(len=*), intent(inout) :: iomsg write (unit, "(a,i0,a)") "n=", dtv%n, ";" end subroutine tw end module m program p use m implicit none type(t) :: v v%n = 5 print *, v end program p

    Answer

    n=5;

    The type writes itself and list-directed output adds one leading blank.

  5. What carries the integer of dt(9) into the procedure?

    Answer

    v_list(1)

    The v_list array holds the parameters of the descriptor.

  6. How does a defined-I/O procedure report a failure?

    Answer

    It sets iostat non-zero and puts a message in iomsg

    The statement then reports the value it was given.

  7. What does gfortran say for an iostat declared INTENT(INOUT)?

    Answer

    Error: DTIO dummy argument must have INTENT OUT

    The six arguments have fixed intents.

  8. Which statements use a defined-I/O procedure?

    Answer

    List-directed output, formatted DT output and internal files of the type

    Every formatted transfer of the type goes through it.

  9. What happens if a defined-I/O procedure writes the whole record again?

    Answer

    It calls itself until the stack ends

    Write the components, never the object.

  10. Can defined I/O write a binary format with its own header?

    Answer

    Not with the formatted form: it writes characters

    A character transfer is not a binary serialiser.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev