Fortran 无法检测文件是否存在

Fortran 无法检测文件是否存在,fortran,intel-fortran,Fortran,Intel Fortran,在我正在改进的一个程序中,我注意到Fortran无法检测文件是否存在。这导致了一个尚未修复的逻辑错误。如果您能指出问题或错误并给我更正,我将不胜感激 open(unit=nhist,file=history,iostat=ierr)!This setting cannot exit program if file does not exist because ierr is always 0 if (ierr /=0) then write(*,*)'!!! error#',ier

在我正在改进的一个程序中,我注意到Fortran无法检测文件是否存在。这导致了一个尚未修复的逻辑错误。如果您能指出问题或错误并给我更正,我将不胜感激

  open(unit=nhist,file=history,iostat=ierr)!This setting cannot exit program if file does not exist because ierr is always 0
  if (ierr /=0) then
   write(*,*)'!!! error#',ierr,'- Dump file not found'
   stop
  endif

  !I used below statement, the program exits even though a file is existing
       open(unit=nhist,file=history,err=700)
   700 ierr=-1
       if (ierr /=0) then
       write(*,*)'!!! error#',ierr,'- Dump file not found'
       stop
       endif

这里有两个截然不同的问题。让我们分开来看

首先,考虑

open(unit=nhist,file=history,iostat=ierr)
       open(unit=nhist,file=history,err=700)
   700 ierr=-1
       if (ierr /=0) then
       ...
注释表明,
ierr
始终设置为零。那么,为什么不应该设置为零呢
ierr
在发生错误时应为非零,但文件是否不存在错误

不一定。如果没有
status=
说明符,则采用默认的
status='unknown'
。如果文件不存在,编译器不必(也不太可能)将在这种情况下打开视为错误。它很可能在书写时根据需要创建它,或者在尝试阅读时抱怨

status='old'
添加到
open
语句是表示“文件应该存在”的常用方式

第二,考虑

open(unit=nhist,file=history,iostat=ierr)
       open(unit=nhist,file=history,err=700)
   700 ierr=-1
       if (ierr /=0) then
       ...
如果此处有错误,执行将转移到标记为
700
的语句。从该语句中,
ierr
被设置为非零值,我们转到
if
构造以处理该错误

只是标记为
700
的语句碰巧也会执行,即使没有错误:它只是
open
之后的下一条语句,没有任何分支会错过它。[我可以举一个这样的分支的例子,但我不想鼓励在现代代码中使用
err=
。使用
iostat=
,事情会更好。]

但如果您只想测试文件的存在,请考虑文件查询:

logical itexists
inquire (file=history, exist=itexists)
if (.not.itexists) error stop "No file :("

有些人会说,这比在
公开声明中使用
status='old'
更好。

亲爱的弗朗西斯卡勒斯,非常感谢!对当我添加“status=old”时,它会起作用。