J. LS
J. LS

Reputation: 123

Fortran formatted write to a specific line

In my code I want to be able to write some data to a file, and then write the number of entries written at the top of the file.

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)

This compiles but it does not work; the only thing written to my file is the correct line number. If I remove that line, the only thing written to the file is 1.

Upvotes: 1

Views: 539

Answers (1)

agentp
agentp

Reputation: 6989

if you only need to direct overwrite the first line you can do like this:

  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

Take care I think the meaning of recl is not standard. Depending on your compiler sometimes the unit is 4 bytes. (or perhaps it is always 1 byte for formatted access. Maybe some standards guru can comment.)

Upvotes: 1

Related Questions