Check whether file has been opened already

Deadly 提交于 2021-02-07 13:10:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!