在Fortran中多次从文件读取同一行 [英] Reading the same line from a file many times in Fortran

查看:367
本文介绍了在Fortran中多次从文件读取同一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Fortran中多次读取文件的同一行.有关数据是真实值.我试图将这段代码作为测试来构建,但是我总是把它弄错了.

I would like to read the same line of a file many time in 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

dat.dat文件包含带有25.325654515464564564

代码返回以下错误.

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

如何解决此错误?

推荐答案

这种非前进输入(使用advance='no')并不意味着文件位置根本不会前进.这意味着文件位置不会超出满足输入列表要求的高度.

Such non-advancing input (using advance='no') doesn't mean that the file position is not advanced at all. It means that the file position isn't advanced beyond what is needed to satisfy the requirements of the input list.

因此,在这种情况下,通过将单个实数"读取到字符变量lnumber中来提高文件位置.下一读将从此后继续.稍后这点恰好是文件的结尾.

So, in this case, the file position is advanced by reading the single "real number" into the character variable lnumber. The next read will continue from this later point. This later point happens to be the end of the file.

更普遍地输入 advancing ,即使不需要全部记录,文件位置也将前进到下一条记录的开头.

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.

作为高性能标记评论,那么反复读同一行可能不是您应该做的.您可以将该行读入一个字符变量中(例如在此处完成),然后将该变量重复用作内部文件.但是,如果您真的想再次阅读一行,请考虑backspace.

As High Performance Mark comments, reading the same line over and over again likely isn't what you should be doing. 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.

这篇关于在Fortran中多次从文件读取同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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