Asking for clarity, I have a series of read lines with END statements. These END statements act as GOTO statements, which I am slowly removing from the code.
I understand that IOSTAT detects EOF and file errors, so believe that I could simply switch out the END statements for the IOSTAT and then react to the IOSTAT value accordingly?
Am I correct in my thinking here?
You are correct: a positive value of IOSTAT means something went wrong with reading the file, a negative value means you reached the end of the file (or the end of a record). Use the ISO_FORTRAN_ENV module to abstract away any specific values of the latter two: IOSTAT_END and IOSTAT_EOR.
That said, if you have a lot of such statements in one unit, then it may still be useful to use the END= clause, as then you can gather all the error handling in a convenient spot in the code.
To avoid goto’s and statement labels for error handling, labelled blocks are working quite nicely (if you don’t mind the additional indentation), we use a construct like this in stdlib:
This file has been truncated.
open(newunit=io, file=filename, form="unformatted", access="stream", iostat=stat)
character(len=:), allocatable :: this_type
integer, allocatable :: vshape(:)
call get_descriptor(io, filename, this_type, vshape, stat, msg)
if (stat /= 0) exit catch
if (this_type /= vtype) then
stat = 1
msg = "File '"//filename//"' contains data of type '"//this_type//"', "//&
& "but expected '"//vtype//"'"
if (size(vshape) /= rank) then
stat = 1
msg = "File '"//filename//"' contains data of rank "//&
& to_string(size(vshape))//", but expected "//&
Most handling of
iostat=stat values happens in subroutines via return or in the main block via
exit catch statements to leave the block and cleanup (close the unit and propagate the error).
Since Fortran 2003, you can call the intrinsic logical functions
is_iostat_eor(stat) to check for end-of-file and end-of-record instead.
and the intrinsic logical functions do not require