0
votes

I want to read an array of double precision values written in a binary file by Matlab into a code in Fortran (compiler gfortran), however my code to read it is not working. Can you please show me the correct way to do it?

Here is my Matlab code, which works.

a=[0.6557 0.0357 0.8491 0.9340 0.6787];

fid=fopen('ft1.bin','w');
fwrite(fid,a,'double');
fclose('all');

fid=fopen('ft1.bin','r');
a2=fread(fid,5,'double');
fclose('all');

a2

Here is my Fortran, code which returns an error when I try to read file ft1.bin

program code1
implicit none

double precision, dimension(5) :: a2
integer :: i

open(1,FILE="ft1.bin",FORM='UNFORMATTED',ACTION='READ')
read(1) a2
close(1)

print *, a2

end program code1

When I try to run it,

gfortran code1.f90 -o bb1
./bb1
At line 8 of file code1.f90 (unit = 1, file = 'ft1.bin')
Fortran runtime error: Unformatted file structure has been corrupted
1

1 Answers

3
votes

One has to avoid the record based I/O with ACCESS="STREAM", e.g.,

PROGRAM test
   IMPLICIT NONE

   INTEGER, PARAMETER :: dp = KIND(1D0)
   INTEGER :: funit, io_stat
   REAL(dp) :: a(5)

   OPEN(NEWUNIT = funit, FILE = 'ft1.bin', STATUS = "OLD", ACCESS = "STREAM", FORM = "UNFORMATTED", IOSTAT = io_stat)
   READ(funit, IOSTAT = io_stat) a
   WRITE(*, *) a
   CLOSE(funit)
END PROGRAM