Can Fortran read bytes directly from a binary file?

后端 未结 1 1515
感情败类
感情败类 2020-12-10 06:36

I have a binary file that I would like to read with Fortran. The problem is that it was not written by Fortran, so it doesn\'t have the record length indicators. So the usu

相关标签:
1条回答
  • 2020-12-10 07:15

    Yes.

    Fortran 2003 introduced stream access into the language. Prior to this most processors supported something equivalent as an extension, perhaps called "binary" or similar.

    Unformatted stream access imposes no record structure on the file. As an example, to read data from the file that corresponds to a single int in the 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 still have issues with endianess and data type size, but those aspects are language independent.

    If you are writing to a language standard prior to Fortran 2003 then unformatted direct access reading into a suitable integer variable may work - it is Fortran processor specific but works for many of the current processors.

    0 讨论(0)
提交回复
热议问题