Fortran 如何以任意顺序读取输入行?

Fortran 如何以任意顺序读取输入行?,fortran,Fortran,我想问一下,我如何能够以任意顺序读取输入行。换句话说:如何读取给定的输入行?我已经编写了下一个测试程序: program main implicit integer*4(i-n) dimension ind(6) do i=1,6 ind(i)=6-i end do open(7,file='test.inp',status='old') do i=0,5 call fseek(7,ind(i+1),0) read(7,*) m

我想问一下,我如何能够以任意顺序读取输入行。换句话说:如何读取给定的输入行?我已经编写了下一个测试程序:

  program main
  implicit integer*4(i-n)
  dimension ind(6)
  do i=1,6
     ind(i)=6-i
  end do
  open(7,file='test.inp',status='old')
  do i=0,5
     call fseek(7,ind(i+1),0)
     read(7,*) m
     write(*,*) m
     call fseek(7,0,0)
  end do
  end
其中test.inp包含:

1
2
3
4
5
6
我的输出是:

4
5
6
2
3
4
有什么问题?我希望

6
5
4
3
2
1

对于文本文件来说,最简单的方法就是只使用空读取来推进行。这将读取使用
unit=iu打开的文件的
nth

       rewind(iu)
       do i=1,n-1
       read(iu,*)
       enddo
       read(iu,*)data
注意:如果你正在从同一个文件中读取一堆文件,你应该考虑将整个文件读入一个字符数组,然后你可以非常简单地按索引访问行。 以下是读取整个文件的示例:

  implicit none
  integer::iu=20,i,n,io
  character(len=:),allocatable::line(:)
  real::x,y
  open(iu,file='filename')
  n=0
  do while(.true.) ! pass through once to count the lines
     read(iu,*,iostat=io)
     if(io.ne.0)exit
     n=n+1
  enddo
  write(*,*)'lines in file=',n
  !allocate the character array. Here I'm hard coding a max line length
  !of 130 characters (that can be fixed if its a problem.)
  allocate(character(130)::line(n))      
  rewind(iu)
  !read in entire file
  do i=1,n 
     read(iu,'(a)')line(i)
  enddo
  !now we can random access the lines using internal reads:
  read(line(55),*)x,y
  ! ( obviously use whatever format you need on the read )
  write(*,*)x,y
  end
一个明显的缺点是,不能像从文件中读取数据一样读取跨多行的数据

编辑:我的gfortran旧版本不喜欢这种可分配字符语法。 这项工作:

 character(len=130),allocatable::line(:)
  ...
 allocate(line(n))

此外,您还可以根据需要调整空间和倒带。
fseek
是一个gfortran扩展,似乎无法正确处理格式化(文本)文件。请注意,它正在寻找字节位置,而不是行,但即使考虑到它的行为最好被描述为bug,如果将
fseek
与格式化读取混合使用,这也是毫无意义的。