-2

I am having trouble reading some floats from a c created binary file. The results are coming out way differently than expected when read into a fortran program. I need any suggestions how to do this.

This is not a duplicate. I have a file in C and i want to read it in fortran:

C data file -> Read in Fortran Code

RobBalmbra
  • 58
  • 8
  • Are you using stream I/O to skip the record length generally added by Fortran? There are many previous questions/answers:, e.g., http://stackoverflow.com/questions/8751185/fortran-unformatted-file-format, http://stackoverflow.com/questions/11569644/can-fortran-read-bytes-directly-from-a-binary-file, http://stackoverflow.com/questions/15190092/how-do-i-read-fortran-binary-file-in-c – M. S. B. Feb 07 '15 at 05:42
  • Im new to fortran only started to use it 2 days ago. Im opening the file using `open (12, file=c,form='unformatted', access='stream', 1 status='old')` Im reading the data sequentially in the file, this is working fine, I have read in unsigned chars, unsigned longs before and after the floats and they work fine. – RobBalmbra Feb 07 '15 at 11:54
  • Reading binary data, such as floating point numbers, that was written by a different system or language can be difficult. You need to find the details of the C format that was written and then work out how to read it in Fortran. Alternatively, work out the detailed format of what the Fortran can read and then make the C write in that format. Stackoverflow is not a free code writing service, you are expected to have tried to answer your question yourself and show the tries. Please read the help pages linked from the top of each Stackoverflow page. – AdrianHHH Feb 08 '15 at 13:45
  • 1
    Check the new duplicate answer, it should be more appropriate. – Vladimir F Героям слава Feb 08 '15 at 14:06

1 Answers1

0

When you write() a binary record in FORTRAN, the layout of the record is:

length_of_data binary_data length_of_data

where length_of_data is a 4 byte integer indicating the number of bytes of the binary_data.

Of course, when you read(), the same format is expected.

In C, a fwrite() will just put the undecorated binary data

binary_data

So you have to either mimic the FORTRAN format from the C fwrite(), or call a C function from FORTRAN for performing the fread()...

EDIT My answer is for FORTRAN up to 95. See the comment of @camelcc for a solution in FORTRAN 2003 (Writing out a binary file from fortran and reading in C)

Community
  • 1
  • 1
aka.nice
  • 9,100
  • 1
  • 28
  • 40
  • 1
    It is much more complicated and varies from compiler to compiler. For example, you can also use direct access even in old Fortran and some compilers do not put any stuff between records, but the are allowed to do that. Also, you forget the format must support records larger than 4 GB. – Vladimir F Героям слава Feb 07 '15 at 17:57