I need help opening multiple files for reading one by one in Fortran. The code below has the right names for the files but overwrites the contents of the file before opening.
How can I stop this from happening
WRITE(FN,10)lam, zeta, (array(k)%str)!,k=1,N)
WRITE(6,*)FN!filename
OPEN(1,FILE=FN, status='replace')
CLOSE(1)
10 FORMAT('4e3_2048_',(I3.0),'_',(I2.2),'_',(A3),'.ksz_cl.txt') !
When you use status='replace'
when opening the files you cause them to be deleted and recreated (Fortran 2018 12.5.6.18):
If REPLACE is specified and the file does exist, the file is deleted, a new file is created with the same name, and the status is changed to OLD.
That's not good when you want to read from the files. Instead, use something like
open(1, file=FN, action='read', status='old', position='rewind')
to ensure: the file exists; it's opened for reading; is positioned at the start of the file.
I have seen status='replace'
intended to mean that the connection is replaced, allowing the unit number to be reused. As can be seen, that's not correct. On that note: unit numbers can be happily reused once a connection is closed. Indeed, if an open
statement refers to a unit already connected to a different file, there's an implied close
on that first connection.