I am struggling with translating a small piece of Fortran code to C. I have a file written in a binary format and a Fortran program that reads that format. My goal is to have a C program that is able to read the same format. I am completely new to Fortran and I do not have the original specification of the format. So, it is kind of a reverse-engineering process.
filename = 'file'
integer :: status
integer, parameter :: di=selected_int_kind(9)
integer(di) :: nn
OPEN(11,file = filename, status = 'old', action = 'read', form = 'unformatted', iostat = status)
if(status /= 0) then
write(*,*) 'FILE ERROR: '//filename
stop
endif
read(11) nn
CLOSE(11)
One thing that really confuses me is the selected_int_kind()
statement. What exactly it does? What would be the equivalent in C?
Actually, my first attempt to translate was pretty much the same as the answer by @JohnBode and it did not work. It reads a totally incorrect value.
After a few more attempts I found a working solution, however, I do not understand why it is so. For some reason the correct value is written in the 5th-8th bytes. So, I can either read two int
values (where the second one will be the correct one), or I can read a long
value and then make a right shift for 32 bits. Any idea why Fortran can so easily retrieve the right value?