向后扫过格式化的流文件

时间:2018-07-18 11:50:23

标签: io fortran gfortran intel-fortran

格式化流I / O出现更多问题。这次我扫描打开的文件以进行格式化的流访问,以了解各行的开头。这是完全成功的。但是,当我尝试使用这些标记向后复制文件时,在ifortgfortran上都遇到问题。该程序:

program testpos2
   implicit none
   character(80) halfline
   character(:), allocatable :: line
   integer iunit
   integer junit
   integer i
   integer, parameter :: N = 4
   integer pos(N)
   integer size
   integer current

   open(newunit=iunit,file='testpos2.txt',status='replace')
   do i = 1, N
      write(halfline,'(*(g0))') i,' 2nd half ',i
      write(iunit,'(*(g0))') trim(halfline)
   end do
   close(iunit)
   allocate(character(len_trim(halfline)) :: line)
   open(newunit=iunit,file='testpos2.txt',status='old',access='stream',form='formatted')
   do i = 1, N
      inquire(iunit,pos=pos(i))
      read(iunit,'()')
   end do
   open(newunit=junit,file='testpos3.txt',status='replace')
   do i = N, 1, -1
      read(iunit,'(a)',pos=pos(i),advance='no',eor=10,size=size) line
      inquire(iunit,pos=current)
      write(*,'(*(g0))') 'pos(i) = ',pos(i),', current = ',current
      write(junit,'(*(g0))',advance='no') line
      do
         read(iunit,'(a)',advance='no',eor=10,size=size) line
         inquire(iunit,pos=current)
         write(*,'(*(g0))') 'pos(i) = ',pos(i),', current = ',current
         write(junit,'(*(g0))',advance='no') line
      end do
10 continue
      write(junit,'(*(g0))') line(1:size)
   end do
end program testpos2

使用gfortran 8.1.0的运行时输出:

pos(i) = 43, current = 55
pos(i) = 29, current = 41
pos(i) = 15, current = 27
pos(i) = 1, current = 13

完美!但是输出文件是:

4 2nd half 4
3 2nd half 3
4 2nd half 4
1 2nd half 1

观察到第三行是错误的! 使用ifort 16.0.2的运行时输出:

pos(i) = 43, current = 55
pos(i) = 29, current = 69
forrtl: severe (24): end-of-file during read, unit -130, file C:\testpos2.txt

第一行之后的输出文件是二进制垃圾。

这看起来很像是内存损坏的结果,但是该程序看起来足够简单,我看不到可能发生损坏的地方,更不用说当向前扫描文件时,ifort和gfortran都能产生预期的结果方向。难道这两个编译器的I / O库都是导致损坏的还是我吗?

0 个答案:

没有答案