Derived type for file

I think Fortran’s representation of file connections as unit numbers is archaic. Is there a derived type for a file that people recommend using?

1 Like

There was a discussion about this in stdlib:

The first outcome was an open function (, but I think no further work was done on a high-level API.

The biggest problem seemed to be how to write generic read and write routines. Without variadic functions, you need to account for all combinatorial possibilities of different types. The other perhaps easier suggestion came from cmacmackin:

This actually wouldn’t be too difficult to implement in a standard library. We’d just write a series of wrappers in C, taking different numbers of void* t arguments. We’d then use interoperability to call these from Fortran and wrap them in a generic block. We could have versions accepting between, say, 1 and 30 arguments (tedious, but could be automatically generated), which should be enough for anyone.

If your files have some specific format, I would recommend just writing your own derived type.

I find I only dislike integer unit numbers when I’m thinking about it away from my code. When I’m writing, they seem fine to me. Using the newunit specifier to give the integer variable a meaningful name helps. The aesthetics of read (param_file, *) ... or write (log_file, "(a)") ... are generally attractive enough for my taste. And in the absence of native variadic functions, I’ll happily use the slightly-crusty-but-powerful I/O statements over a derived type with a million overloads to achieve the same thing.