Read out Fortran unformatted file in C

Try the following. I hope I haven’t make any typo/mistake.
This assumes that the file was written with the same endianness as it is being read.

#include <stdio.h>

// main array, cols and rows inverted to speed up reading
// (Fortran stores and saves, by default, arrays columnwise
static double VArPolar[50001][2001]; 

int main(int argc, char *argv[])
{
  int ir, ict;
  double val;
  char *filename="BaPolar";  // make sure the filename is right
  FILE *fp;

  if ((fp=fopen(filename,"rb")) == NULL) {
    fprintf(stderr, "error opening file %s\n", filename);
    return 1;
  }
  for (ir=0; ir<50001; ir++) {
    if (fread(VArPolar[ir],8,2001,fp) != 2001) {
      fprintf(stderr, "error reading row no. %d\n", ir+1);
      return 2;
    }
  }
  fclose(fp);
  // now the array is read
  // to access Fortran element (i,j) (-1000:1000,0:50000)
  // use VArPolar[j][i+1000]
  printf("%g %g\n",VArPolar[0][0],VArPolar[0][1]);
  return 0;
}
1 Like