fortran - 打开文件或创建文件和追加数据的单个命令

标签 fortran fortran90

我想知道在 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/

    相关文章:

    fortran90 - Fortran 中的 LAPACK/BLAS 矩阵乘法返回零

    function - 具有假定形状虚拟参数的过程必须具有显式接口(interface)

    python - 在不知道数据大小的情况下从文件中读取 float 作为 numpy 数组

    linux - Sublime Text 2 构建 (Ctrl +B) 英特尔 Fortran 编译器

    fortran - 如何从文本文件中读取 Fortran 90 中的行数?

    Fortran 中的接口(interface)类型绑定(bind)过程

    c - 在 C++/Fortran 中集成贝塞尔函数

    fortran - 在 Fortran 主文件头中包含 .f 和 .F90 文件

    c++ - 混合 C++ 和 Fortran 代码的问题

    segmentation-fault - 为什么 Fortran 代码会出现段错误?