Reputation: 1360
I am trying to read a binary file consisting of signed 16 bit integers and there are exactly 51840000 of them. The code in C
that accomplishes this looks like this:
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
int main()
{
int16_t *arr = malloc(51840000*sizeof(int16_t));
FILE *fp;
fp = fopen("LDEM_45N_400M.IMG", "rb");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fread() function: \n\n");
fread(arr, sizeof(*arr), 51840000, fp);
fclose(fp);
printf("%d \n", arr[51840000-2]);
free(arr);
return 0;
}
How would i read such a file in Fortran? IO in Fortran has always been very mysterious to me.
Upvotes: 1
Views: 489
Reputation: 60008
Use access="stream"
and you can read it the same way. Declare your integers as integer(int16)
and use the iso_fortran_env
module.
use iso_fortran_env
integer :: ierr, n = 51840000
integer(int16) :: arr(n)
open(newunit=iu,file="LDEM_45N_400M.IMG", access="stream", status="old", action="read",iostat=ierr)
if (ierr/=0) stop "Error opening the file."
read(iu, iostat=ierr) arr
if (ierr/=0) stop "Error reading the array."
close(iu)
Upvotes: 4