如何知道我们在Fortran 77中达到了EOF? [英] How to know that we reached EOF in Fortran 77?

查看:165
本文介绍了如何知道我们在Fortran 77中达到了EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我们假设我有以下子程序:

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.

推荐答案

以下是两种方法.我拒绝讲授过25年以上不应使用或过时的过时的Fortran 77,但第一种方法应该适用于从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

方法1:

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

方法2:

这需要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屋!

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