如何知道我们在 Fortran 77 中达到了 EOF? [英] How to know that we reached EOF in Fortran 77?
问题描述
所以假设我有以下子程序:
So let's assume that I have the following subroutine:
subroutine foo(a_date)
character*10 dummy, a_date
open(unit=1,file='ifile.txt',status='old')
read(1, 100) dummy
100 format(A10)
a_date = dummy
return
end
它只从文件中读取一行.但我想递归地阅读所有的行.因此,当我在主程序中递归调用子程序时,在达到 EOF 后出现错误.那么有没有办法阻止它,以便程序知道我何时到达EOF?基本上,我希望能够知道何时到达 EOF.
which only reads a line from the file. But I want to read all the lines recursively. So when I call the subroutine recursively in my main procedure, I get an error after reaching EOF. So is there a way to prevent it so that the program knows when I reach EOF? Basically, I want to be able to know when I reach EOF.
推荐答案
这里有两种方法.我拒绝教授过时的 Fortran 77,它不应该在 25 年内使用或教授过,但第一种方法应该适用于从 77 开始的任何版本的 Fortran
Here are two methods. I refuse to teach the obsolete Fortran 77 which shouldn't have been used or taught in 25 years+, but the first method should work in any version of Fortran from 77 onwards
方法一:
ijb@ianbushdesktop ~/stackoverflow $ cat data.dat
1
2
3
ijb@ianbushdesktop ~/stackoverflow $ cat end.f90
Program eof
Implicit None
Integer :: data
Open( 10, file = 'data.dat' )
Do
Read( 10, *, End = 1 ) data
Write( *, * ) data
End Do
1 Write( *, * ) 'Hit EOF'
End Program eof
ijb@ianbushdesktop ~/stackoverflow $ gfortran -std=f2003 -Wall -Wextra -O -fcheck=all end.f90
ijb@ianbushdesktop ~/stackoverflow $ ./a.out
1
2
3
Hit EOF
方法二:
这需要 F2003,但这就是你现在应该使用的
This needs F2003, but that's what you should be using these days
ijb@ianbushdesktop ~/stackoverflow $ cat data.dat
1
2
3
ijb@ianbushdesktop ~/stackoverflow $ cat end2.f90
Program eof
Use, intrinsic :: iso_fortran_env, Only : iostat_end
Implicit None
Integer :: data, error
Open( 10, file = 'data.dat' )
Do
Read( 10, *, iostat = error ) data
Select Case( error )
Case( 0 )
Write( *, * ) data
Case( iostat_end )
Exit
Case Default
Write( *, * ) 'Error in reading file'
Stop
End Select
End Do
Write( *, * ) 'Hit EOF'
End Program eof
ijb@ianbushdesktop ~/stackoverflow $ gfortran -std=f2003 -Wall -Wextra -O -fcheck=all end2.f90
ijb@ianbushdesktop ~/stackoverflow $ ./a.out
1
2
3
Hit EOF
这篇关于如何知道我们在 Fortran 77 中达到了 EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!