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

Fortran ≤2003中处理多退出点的最优方式及代码优化建议

Fortran ≤2003标准下的IO错误处理代码选择与优化建议

我有一段被Python调用的Fortran文件读取代码,需要处理全部或大部分IO错误,避免Python代码因无合理报错信息而崩溃。为此我编写了两种实现方式:

第一种实现:存在多退出点和代码重复

subroutine read_params(filename, params, ierr)
  implicit none
  ! Argument Declarations !
  character(len=*), intent(in) :: filename
  integer, dimension(4), intent(out) :: params
  integer, intent(out) :: ierr
  ! Variable Declarations
  integer :: i, iounit, ios
  character(len=:), allocatable :: errmsg

  iounit = 1
  ierr = 0 ! Initialize error code
  allocate(character(len=256+len(filename)) :: errmsg)
  open(unit=iounit, status="old", file=filename, form="unformatted", iostat=ios, iomsg=errmsg)
  call check_for_io_errors(ios, "open", ierr, errmsg)
  if (ierr /= 0) then
      close(iounit)
      return
  end if
  read(iounit, *, iostat=ios, iomsg=errmsg) (params(i), i=1, 4)
  call check_for_io_errors(ios, "read", ierr, errmsg)
  if (ierr /= 0) then
      close(iounit)
      return
  end if
  close(iounit)

end subroutine read_params

第二种实现:使用goto语句的版本

subroutine read_params(filename, params, ierr)
  implicit none
  ! Argument Declarations !
  character(len=*), intent(in) :: filename
  integer, dimension(4), intent(out) :: params
  integer, intent(out) :: ierr
  ! Variable Declarations
  integer :: i, iounit, ios
  character(len=:), allocatable :: errmsg

  iounit = 1
  ierr = 0 ! Initialize error code
  allocate(character(len=256+len(filename)) :: errmsg)
  open(unit=iounit, status="old", file=filename, form="unformatted", iostat=ios, iomsg=errmsg)
  call check_for_io_errors(ios, "open", ierr, errmsg)
  if (ierr /= 0) then
      goto 10
  end if
  read(iounit, *, iostat=ios, iomsg=errmsg) (params(i), i=1, 4)
  call check_for_io_errors(ios, "read", ierr, errmsg)
  if (ierr /= 0) then
      goto 10
  end if
10 close(iounit)

end subroutine read_params

请问在Fortran ≤ 2003标准中,哪种方式是首选方案?此外,若有其他代码优化建议,欢迎告知。


参考:check_for_io_errors子程序源码

subroutine check_for_io_errors(ios, operation, ierr, errmsg)
  implicit none
  ! Argument Declarations !
  integer, intent(in) :: ios
  character(len=*), intent(in) :: operation
  integer, intent(out) :: ierr
  character(len=*), intent(in) :: errmsg

  if (ios /= 0) then
      if (operation == "open") then
          ierr = -1
          print *, "Error opening file"
          print *, "Error message: " // trim(errmsg)
      else if (operation == "read") then
          ierr = -2
          print *, "Error reading file"
          print *, "Error message: " // trim(errmsg)
      else if (operation == "write") then
          ierr = -3
          print *, "Error writing file"
          print *, "Error message: " // trim(errmsg)
      end if
  end if

end subroutine check

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:52:34