1

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.

0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.