简体   繁体   English

在Fortran中多次从文件读取同一行

[英]Reading the same line from a file many times in Fortran

I would like to read the same line of a file many time in Fortran. 我想在Fortran中多次读取文件的同一行。 The concerned data are real values. 有关数据是真实值。 I tried to build this code as test but I am always getting it wrong. 我试图构建此代码作为测试,但是我总是把它弄错。

program advance

    implicit none
    integer , parameter :: ut = 20
    character(len=7) :: fname = 'dat.dat'
    integer :: n, idx 
    character(len=100) :: lnumber 
    open(unit = ut, file =fname, status='old', action='read')

    n = 10 

    do idx = 1, n 
        read(ut, '(a)', advance = 'no') lnumber 
        print *, lnumber 
    end do 

end program advance

The dat.dat file contains one line with 25.325654515464564564 dat.dat文件包含一行25.325654515464564564

The code return the following error. 该代码返回以下错误。

At line 13 of file advance.f90 (unit = 20, file = 'dat.dat')
Fortran runtime error: End of record

How do I fix this bug? 如何解决此错误?

Such non-advancing input (using advance='no' ) doesn't mean that the file position is not advanced at all. 这种非高级输入(使用advance='no' )并不意味着文件位置根本没有高级。 It means that the file position isn't advanced beyond what is needed to satisfy the requirements of the input list. 这意味着文件位置不会超出满足输入列表要求所需的位置。

So, in this case, the file position is advanced by reading the single "real number" into the character variable lnumber . 因此,在这种情况下,通过将单个“实数”读入字符变量lnumber来提高文件位置。 The next read will continue from this later point. 下一读将从此后继续。 This later point happens to be the end of the file. 稍后这点恰好是文件的末尾。

With advancing input more generally, the file position is advanced to the start of the next record even if the record is not required in entirety. 随着越来越多的一般推进输入,文件位置是先进的,即使在整体不要求记录的下一个记录的开始。


As High Performance Mark comments , reading the same line over and over again likely isn't what you should be doing. 正如High Performance Mark 所说 ,一遍又一遍地阅读同一行不是您应该做的。 You could read the line into a character variable (such as is done here) and repeatedly use that variable as an internal file . 您可以将该行读入一个字符变量(例如在此处完成),然后将该变量重复用作内部文件 However, if you really want to read a line again, consider backspace . 但是,如果您真的想再次读取一行,请考虑backspace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM