我想知道在 Fortran 中是否可以只使用一个命令(带有选项/说明符)来执行以下操作:
(这可以通过:
open(unit=40,file='data.data',Access = 'append',Status='old')
完成,但如果文件不存在,则会发出运行时错误)我目前正在使用
inquire
检查文件是否存在,但我仍然必须使用 open
附加或写入数据的语句。
最佳答案
据我所知,唯一安全的解决方案是按照您已经在做的方式,使用不同的 open
针对不同情况的声明:
program proba
implicit none
logical :: exist
inquire(file="test.txt", exist=exist)
if (exist) then
open(12, file="test.txt", status="old", position="append", action="write")
else
open(12, file="test.txt", status="new", action="write")
end if
write(12, *) "SOME TEXT"
close(12)
end program proba
您可能对我的 Fortran interface library to libc file system calls (modFileSys) 感兴趣,这至少可以省去逻辑变量和
inquire
直接查询文件状态的语句:if (file_exists("test.txt")) then
...
else
...
end if
但是当然你可以很容易地自己编写一个类似的函数,尤其是它不会让你摆脱这两个
open
声明...
关于fortran - 打开文件或创建文件和追加数据的单个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15526203/