You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran如何读取含51840000个有符号16位整数的二进制文件

Fortran实现读取16位有符号整数二进制文件代码
program read_16bit_bin
    use, intrinsic :: iso_fortran_env, only: int16
    implicit none
    integer(int16), allocatable :: arr(:)
    integer :: fp, ierr
    integer, parameter :: N = 51840000

    ! 分配数组空间,对应C代码中的malloc逻辑
    allocate(arr(N), stat=ierr)
    if (ierr /= 0) then
        write(*,*) "数组内存分配失败"
        stop 1
    end if

    ! 打开二进制文件,流访问模式和C的rb读取逻辑完全对齐
    open(newunit=fp, file="LDEM_45N_400M.IMG", form='unformatted', access='stream', status='old', action='read', iostat=ierr)
    if (ierr /= 0) then
        write(*,*) "Error opening file"
        deallocate(arr)
        stop 1
    end if

    write(*,*) "Testing fread() equivalent function: "//new_line('a')
    ! 批量读取所有16位整数到数组
    read(fp) arr
    close(fp)

    ! Fortran数组下标从1开始,对应C的arr[51840000-2]取倒数第二个元素
    write(*,*) arr(N-1)

    ! 释放内存
    deallocate(arr)
end program read_16bit_bin

关键说明

  • 引入iso_fortran_env内置模块的int16类型,和C的int16_t完全对应,确保整数位宽、符号规则一致
  • 打开文件必须指定access='stream',这是Fortran2003开始支持的流访问模式,不会插入Fortran默认无格式IO的记录长度标记,避免读取内容错位
  • newunit是Fortran2008特性,自动分配未被占用的文件单元号,避免手动指定的冲突问题;如果编译器版本过旧不支持,可替换为手动指定单元号,比如将open语句改为open(10, file="LDEM_45N_400M.IMG", ...),后续读写、关闭操作都用单元号10即可

编译运行示例

使用gfortran编译的命令为:
gfortran -o read_16bit read_16bit.f90
编译完成后直接运行生成的可执行文件即可。

内容的提问来源于stack exchange,提问作者atapaka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:36:07