文件不存在时的异常处理

use*_*364 3 fortran

我有一个Fortran程序,它从打开和读取.txt文件中的数据开始.在程序结束时,将写入一个新文件,该文件将替换旧文件(最初导入的文件).

但是,可能会发生需要打开的文件不存在,对于这种情况,应该从.txt文件导入的变量应该是0.

我想通过下面的代码执行此操作,但是这不起作用,并且当文件history.txt不存在时脚本被中止.

history.txt文件不存在时,如何让脚本将默认值设置为我的变量?

  OPEN(UNIT=in_his,FILE="C:\temp\history.txt",ACTION="read")
  if (stat .ne. 0) then    !In case history.txt cannot be opened (iteration 1)
    write(*,*) "history.txt cannot be opened"
    KAPPAI=0
    KAPPASH=0
    go to 99
  end if
  read (in_his, *) a, b
  KAPPAI=a
  KAPPASH=b
  write (*, *) "KAPPAI=", a, "KAPPASH=", b
  99   close(in_his)  
Run Code Online (Sandbox Code Playgroud)

导入的文件非常简单,如下所示:

  9.900000000000006E-003  3.960000000000003E-003
Run Code Online (Sandbox Code Playgroud)

Tim*_*own 6

我会IOSTAT像@Fortranner所说的那样使用.在尝试打开文件之前我也会设置默认值,而我倾向于不使用goto.如:

program test

    implicit none
    integer :: in_his, stat
    real :: KAPPAI, KAPPASH

    in_his  = 7
    KAPPAI  = 0
    KAPPASH = 0

    OPEN(UNIT=in_his, FILE="history.txt",ACTION='read',IOSTAT=stat,STATUS='OLD')
    if (stat .ne. 0) then
            write(*,*) "history.txt cannot be opened"
            stop 1
    end if

    read (in_his, *) KAPPAI, KAPPASH
    close(in_his)

    write (*, *) "KAPPAI=", KAPPAI, "KAPPASH=", KAPPASH

end program test
Run Code Online (Sandbox Code Playgroud)