如果从文件中读取错误,如何使用关闭语句?

How to use close statement in case of reading error from file?

我的IDE是:

Code::Blocks 20.3(编译器:mingw 9.2.0)

示例代码为:

module mod_close_file

implicit none

integer :: n_something

contains

function proc_calling() result(err_loc)

  logical :: err_loc

  err_loc = .false.

  open( unit = 15, file = 'data_aa.txt', action = 'read', status = 'old', err = 100 )

    read(15,*, err = 101) n_something

  close(unit = 15, status = 'keep' )

return

100 write(*,'(5x,a)') "err_loc - proc_calling - reading format - 100"
err_loc = .true.
!close(unit = 15, status = 'keep' )

return

101 write(*,'(5x,a)') "err_loc - proc_calling - reading format - 101"
err_loc = .true.
!close(unit = 15, status = 'keep' )

end function proc_calling

end module mod_close_file

program close_file

use, non_intrinsic :: mod_close_file

implicit none

logical :: err_glo

err_glo = proc_calling()

if ( err_glo ) stop "err_glo - proc_calling"

end program close_file

如果指定文件中的值n_something不是整数,程序将报错。那么,是否需要在return命令后写关闭命令?

你问的是,是否需要在停止执行之前关闭文件,或者它是否会自动关闭? Fortran 2008 Final Draft 9.5.7.1-6(第 211 页):

During the completion step (2.3.5) of termination of execution of a program, all units that are connected are closed.

2.3.5-4(第 33 页):

Normal termination of execution of an image is initiated when a STOP statement or end-program-stmt is executed.

所以不,您不需要在调用 STOP 之前关闭它,它应该在不调用 close 的情况下关闭。 (我个人无论如何都会这样做)