2017-01-09 117 views
1

在我正在改进的程序中,我注意到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 

回答

2

这里有两个不同的问题。我们分别看看它们。

首先,考虑

open(unit=nhist,file=history,iostat=ierr) 

的意见建议,ierr总是被设置为零。那么,为什么不应该它被设置为零? ierr应该在非零的情况下出现错误,但是文件不存在错误?

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

status='old'添加到open声明是通常说“文件应存在”的方式。

二,审议

 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'open声明中。

+0

亲爱的Francescalus,非常感谢你!是。它在我添加'status = old'时起作用。 – Leon