As of now I am checking if iostat is smaller than 0 and re-open the file if a namelist could not be found (which is really ugly), i.e.:
read(100, nml=nm_tensor, iostat = ios)
if (ios < 0) then
close(100)
open(100, file="input_nm", status='old', action="read", iostat = ios)
end if
How do I check if a namelist is present in a file before reading it in? Is there a more elegant way for recovering when a namelist was not present and lead to an end-of-file error?
Say the file you're reading is:
&INT_NAMELIST
A = 1,
B = 2
/
&REAL_NAMELIST
X = 3.15,
Y = 2.71
/
Then the program
INTEGER :: A, B
REAL :: X, Y
NAMELIST /INT_NAMELIST/ A, B
NAMELIST /REAL_NAMELIST/ X, Y
OPEN(unit=100, action="READ", status="OLD")
read(100, nml=INT_NAMELIST)
read(100, nml=REAL_NAMELIST)
will work, but change the order of read statements, and it won't:
read(100, nml=REAL_NAMELIST)
read(100, nml=INT_NAMELIST)
because it has read past the INT_NAMELIST
until it found and read the REAL_NAMELIST
. If you are not sure of the order of namelists in the file, you should use a REWIND
before every new namelist to be read, resetting the file position to the beginning of the file:
read(100, nml=REAL_NAMELIST)
rewind(100)
read(100, nml=INT_NAMELIST)