我想通过Matlab将二进制文件中写入的双精度值数组读入Fortran中的代码(编译器gfortran),但是我的代码读取它不起作用。你能告诉我正确的方法吗?
这是我的Matlab代码,可以使用。
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
这是我的Fortran代码,当我尝试读取文件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
当我尝试运行它时,
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
答案 0 :(得分:3)
必须避免record based I/O ACCESS="STREAM"
,例如
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