Unexpected "padding" in a Fortran unformatted file

Andrew Spott picture Andrew Spott · Jan 6, 2012 · Viewed 33k times · Source

I don't understand the format of unformatted files in Fortran.

For example:

open (3,file=filename,form="unformatted",access="sequential")
write(3) matrix(i,:)

outputs a column of a matrix into a file. I've discovered that it pads the file with 4 bytes on either end, however I don't really understand why, or how to control this behavior. Is there a way to remove the padding?

Answer

M. S. B. picture M. S. B. · Jan 6, 2012

For unformated IO, Fortran compilers typically write the length of the record at the beginning and end of the record. Most but not all compilers use four bytes. This aids in reading records, e.g., length at the end assists with a backspace operation. You can suppress this with the new Stream IO mode of Fortran 2003, which was added for compatibility with other languages. Use access='stream' in your open statement.