jshep
jshep

Reputation: 241

Write to and replace a file multiple times in Fortran

I'm trying to run a code that takes a particularly long time. In order for it to complete, I've separated the time step loops as such so that the data can be dumped and then re-read for the next loop:

do 10 n1 = 1, 10
  OPEN(unit=11,file='Temperature', status='replace')
  if (n1.eq.1) then
    (set initial conditions)
  elseif (n1.gt.1) then
  READ(11,*) (reads the T values from 11)
  endif

  do 20 n = 1, 10000
    (all the calculations for new  T values)
    WRITE(11,*) (overwrites the T values in 11 -  the file isn't empty to begin with)
20    continue

10    continue

My issue then is that this only works for 2 time n1 time steps - after it has replace file 11 once, it no longer replaces and just reiterates the values in there.

Is there something wrong with the open statement? Is there a way to be able to replace file 11 more than once in the same code?

Upvotes: 4

Views: 1474

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

Your program will execute the open statement 10 times, each time with status = 'replace'. On the first go round presumably the file does not exist so the open statement causes the creation of a new, empty, file. On the second go round the file does exist so the open statement causes the file to be deleted and a new, empty, file of the same name to be created. Any attempt to read from that file is likely to cause issues.

I would lift the initial file opening out of the loop and restructure the code along these lines:

open(unit=11,file='Temperature', status='replace')
(set initial conditions)
(write first data set into file)

do n1 = 2, 10
  rewind(11)
  read(11,*) (reads the T values from 11)
  ! do stuff
  close(11)   ! Not strictly necessary but aids comprehension of intent
  ! Now re-open the file and replace it
  open(unit=11,file='Temperature', status='replace')
  do n = 1, 10000
      (all the calculations for new  T values)
      write(11,*) (overwrites the T values in 11 -  the file isn't empty to begin with)
  end do
end do

but there is any number of other ways to restructure the code; choose one that suits you.

In passing, passing data from one iteration to the next by writing/reading a file is likely to be very slow, I'd only use it for checkpointing to support restarting a failed execution.

Upvotes: 5

Related Questions