问题
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?
回答1:
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.
回答2:
you can use inquire
:
logical itsopen
inquire(unit=3, opened=itsopen)
if ( itsopen ) then
write(*,*) 'Its open already'
else
open(3,'myfile.txt')
end if
来源:https://stackoverflow.com/questions/31941681/check-whether-file-has-been-opened-already