How do I read fortran binary file in C?

后端 未结 3 443
遥遥无期
遥遥无期 2021-01-20 04:33

I have a binary file generated by fortran code. This file contains an array of doubles. I need to open it in my C program and then work with it as with an usual array.

3条回答
  •  抹茶落季
    2021-01-20 04:45

    Almost all Fortran compilers, for unformatted (i.e., binary) sequential files, write the length of the record at the beginning and end of each record. Typically the length is written in four bytes, though some compilers use eight bytes. A record is everything that is written with a single Fortran write statement. If this array was written with a single Fortran write statement with this type of file, then you have four or eight bytes to skip over, then the array, then four or eight extra bytes. You can probably figure this out by viewing the file with a hex editor. If the array was written in pieces (e.g., by columns or rows) with multiple write statements, each record will have this structure.

    If the file is written by Fortran as unformatted, the Fortran double type is written in the binary representation of that computer. You should be able to read it in C on the same computer type. If you are changing architectures and not just languages the binary representation might be different.

    Fortran has other file access methods which don't include the record length information. Direct access, for example. The new method of stream access is designed for inter-language compatibility.

    If the array is multi-dimensional you may want to transpose it because Fortran has column-major arrays while C uses row-major.

    Related questions: Fortran unformatted file format and reading fortran unformatted file with python

提交回复
热议问题