Can Fortran read bytes directly from a binary file?

I have a binary that I would like to read using Fortran. The problem is that it was not written by Fortran, so it has no record length indicators. Therefore, plain Fortran plain reading will not work.

I had the thought that I could succumb and read the file as a formatted file, byte (or 4 bytes to 4 bytes, really) into an array of characters, and then convert the contents of the characters to integers and floats through a transfer function or terrible equivalence instruction. But this does not work: I try to read 4 bytes at a time and, according to the POS conclusions from the statement inquire, reading skips about 6,000 bytes or so, and the character array is loaded using spam.

Then no. Are there any details in this approach that I forget? Or is there just a fundamentally different and better way to do this in Fortran? (BTW, I also tried reading into an array integer*1and an array of bytes. Although these codes were compiled when it came to the read statement, the code crashed.)

+5
source share
1 answer

Yes.

Fortran 2003 introduced streaming language access. Prior to this, most processors supported something equivalent as an extension, possibly called β€œbinary” or similar.

Unformatted stream access does not create record structures in a file. For example, to read data from a file corresponding to a single int in a Companion C processor (if any) for a particular Fortran processor:

USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_INT
INTEGER, PARAMETER :: unit = 10
CHARACTER(*), PARAMETER :: filename = 'name of your file'
INTEGER(C_INT) :: data
!***
OPEN(unit, filename, ACCESS='STREAM', FORM='UNFORMATTED')
READ (unit) data
CLOSE(unit)
PRINT "('data was ',I0)", data

You may have problems with endianess size and data type, but these aspects are language independent.

If you write a language standard before Fortran 2003, then an unformatted read direct access to a suitable integer variable may work - this is a Fortran processor, but it works for many current processors.

+8
source

All Articles