单个命令打开文件或创建它和追加数据 [英] Single command to open a file or create it and the append data

查看:150
本文介绍了单个命令打开文件或创建它和追加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Fortran中是否可以使用一个命令(包含options / specifiers)来执行以下操作:


  1. 打开一个文件,如果存在并附加一些数据
    (这可以通过: open(unit = 40,file ='data.data',Access =' append',Status ='old')但是如果文件不存在,则会发出运行时错误)

  2. 创建文件如果它不存在并写入一些数据。

我目前使用 inquire code>来检查文件是否存在,但是我仍然必须使用 open 语句来附加或写入数据。


打开针对不同情况的报表:

 程序概率
隐式无

逻辑::存在

查询(fil e =test.txt,exists = exists)
if(exists)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

您可能对我的用于libc文件系统调用(modFileSys)的Fortran接口库感兴趣,它可能会通过直接查询文件状态,最少让你的逻辑变量和查询语句:

  if(file_exists(test.txt))then 
...
else
...
end if

但是你当然可以很容易地编写一个类似的函数,特别是它不会让你从两个打开报表...


I would like to know if in Fortran it is possible to use just a single command (with options/specifiers) to do the following:

  1. open a file if it exists and append some data (this can be done with: open(unit=40,file='data.data',Access = 'append',Status='old') but if the file does not exist a runtime error is issued)

  2. create the file if it does not exist and write some data.

I am currently using inquire to check whether the file exist or not but then I still have to use the open statement to append or write data.

解决方案

As far as I am aware of, the only safe solution is to do the way you're already doing it, using different open statements for the different cases:

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

You may be interested in my Fortran interface library to libc file system calls (modFileSys), which could at least spare you the logical variable and the inquire statement by querying the file status directly:

if (file_exists("test.txt")) then
    ...
else
    ...
end if

but of course you can program a similar function easily yourself, and especially it won't save you from the two open statements...

这篇关于单个命令打开文件或创建它和追加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆