首页 > 解决方案 > 在 Fortran 中读取二进制文件

问题描述

我正在尝试读取一个由带符号的 16 位整数组成的二进制文件,其中正好有 51840000 个。完成此操作的代码C如下所示:

#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;
}

我将如何在 Fortran 中读取这样的文件?Fortran 中的 IO 对我来说一直很神秘。

标签: fortrangfortranfortran90intel-fortran

解决方案


使用access="stream",您可以以相同的方式阅读它。将您的整数声明为integer(int16)并使用该iso_fortran_env模块。

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)

推荐阅读