我有一个从 .txt
文件打开和读取数据的 Fortran 程序。
在程序结束时会写入一个新文件,它会替换旧文件(最初导入的)。
但是可能会出现需要打开的文件不存在的情况,在这种情况下,应该从 .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)
导入的文件非常简单,如下所示:
9.900000000000006E-003 3.960000000000003E-003
最佳答案
我会使用@Fortranner 所述的IOSTAT
。我还会在尝试打开文件之前设置默认值,而且我倾向于不使用 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
关于fortran - 文件不存在时的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110923/