2017-01-09 75 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