I/O past end of record on unformatted file when reading a binary file in fortran with form='unformatted'

Viewed 161

I try to read a binary file using form='unformatted' in Fortran-90 created by this C++ program:

#include<iostream>
#include<assert.h>
#include<cmath>

template<typename T>
void write_binary_f_all(T *__restrict__ a,int size_a,const std::string &filename)
{
    int dummy;
    FILE *fp;
    if((fp = fopen(filename.data(),"wb")) == NULL){
        printf("cannot open %s\n",filename.data());
        exit(1);
    }
    dummy = size_a;
    assert(fwrite(&dummy,sizeof(int),1,fp) == 1); // header
    assert(fwrite(a,sizeof(T),size_a,fp) == size_a);
    assert(fwrite(&dummy,sizeof(int),1,fp) == 1); // tail
    fclose(fp);
}

int main(){
    float a[10];
    for(int i=0;i<10;i++){
        a[i] = exp(-i * 20. / 13.21);
        printf("%e ",a[i]);
    }
    printf("\n");
    write_binary_f_all(a,10,"out.bin");
}

Then in Fortran, I use this block to read this binary file:

program main 
implicit none

real a(10)
integer i
open(10,file='out.bin',status='old',form='unformatted')
read(10) a(:)
print*,a 
close(10)

But this error was raised Fortran runtime error: I/O past end of record on unformatted file. I use gcc-9.3 compiler on Ubuntu-20.04. What is the problem?

0 Answers
Related