Fortran格式化写入特定行

时间:2015-11-19 12:31:54

标签: file-io fortran

在我的代码中,我希望能够将一些数据写入文件,然后写入文件顶部写入的条目数。

open(unit = 107, file = '/.data', access = 'direct', status = 'replace', recl = 200,&
form = 'formatted')
linecounter = 0 
do i = 1, N
    do j = 1, 4
        write(107, '(I3)', rec = linecounter + 1) [some data(i, j)]
        linecounter = linecounter + 1
    end do 
end do 
do i = 1, 2*N
    do k = 1, 2
        do j = 1, 4 
            if ([some condition]) then
            write(107, '(I3)', rec = linecounter + 1) [some data(i, j, k)]
            linecounter = linecounter + 1
            end if 
        end do
    end do
end do
write(107, '(I4)', rec = 1) linecounter
close(107)

这编译但不起作用;写入我文件的唯一内容是正确的行号。如果删除该行,则写入该文件的唯一内容是1.

1 个答案:

答案 0 :(得分:1)

如果需要直接覆盖第一行,你可以这样做:

  implicit none
  integer i,j
  open(20,file='test') ! open to write actual data sequential access.
  write(20,'(16a)')(' ',i=1,16)  ! placeholder for header
  do i=1,10
     write(20,*)(j,j=1,i)  ! arbitrary data, different lengths each line
  enddo         
  close(20)
  ! reopen direct access
  open(20,file='test',form='formatted',access='direct',recl=16)
  ! note recl is exactly the placeholder length.
  write(20,'(2i8)',rec=1)0,42
  ! take care to write exactly recl bytes - some compilers will blank pad
  ! for you if you write less than a full record, but i wouldn't count on it.
  close(20)
  end

注意我认为recl的含义不是标准的。根据您的编译器,有时单位为4个字节。 (或者,对于格式化访问,它可能总是1个字节。也许一些标准专家可以发表评论。)