I am writing a file reading library, and need to check whether a file has been opened so that I can skip the open statement and go directly to a read.
How can this be achieved in fortran?
When one wants to know about connections to external files there is the inquire
statement. There are two forms to this: inquire by file; inquire by unit.
tom's answer shows inquire by unit. This tests whether unit 3 is connected to any file. One could then go on to ask the name of the connected file with the name=
and named=
specifiers.1
Inquire by file allows one to ask: is a given file connected to any unit, and if so, to which unit?
inquire(file=filename, number=unit)
If the file is not connected then unit
will be -1
, otherwise unit
will correspond to the unit connected to the file.
Alternatively, depending on what you want to do with the open
statement, it isn't necessarily erroneous to open
with an already connected file.
[1] The variable in the name=
specifier will become undefined if the file has no name. Testing this variable against the desired filename when it is undefined is bad. The named=
specifier allows detection of this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With