文件不存在时的异常处理 [英] Exception handling when the file does not exist

查看:156
本文介绍了文件不存在时的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Fortran program that starts with opening and reading data from a .txt file. At the end of the program a new file is written, which replaces the old file (that was originally imported).

然而,可能会出现文件需要打开的文件不存在,在这种情况下,应该从 .txt 文件导入的变量应该是 0

However it can occur that the file that needs to be opened does not exists, for that case the variables that should be imported from the .txt file should be 0.

我认为通过下面的代码来做到这一点,但是这不起作用,当文件 history.txt 不存在。

I thought by doing this with the code below, however this does not work and the script is aborted when the file history.txt does not exists.

如何在 history.txt file does not exist?

How can I let the script set default values to my variables when the history.txt file does not exists?

  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)  

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

The file that is imported is pretty simple and looks like:

  9.900000000000006E-003  3.960000000000003E-003


推荐答案

我会用 IOSTAT ,如@Fortranner所述。在尝试打开文件之前,我还会设置默认值,并且我倾向于不使用goto。如:

I would use IOSTAT as stated by @Fortranner. I would also set defaults before trying to open the file and I tend not to use goto's. As in:

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

这篇关于文件不存在时的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆