Single command to open a file or create it and the

2020-02-27 04:45发布

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.

4条回答
该账号已被封号
2楼-- · 2020-02-27 05:22

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...

查看更多
孤傲高冷的网名
3楼-- · 2020-02-27 05:30

In open statement add the attribute access as follows;

Open(unit=031,file='filename.dat',form='formatted',status='unknown',access='append')

The above statement will open the file without destroying old data and write command will append the new lines in the file. The simplest solution for fortran 90.

查看更多
在下西门庆
4楼-- · 2020-02-27 05:34

if you replace the status from 'old' to 'unknown' then you will not get the run time error if the file exists or now.

Thanks

查看更多
Deceive 欺骗
5楼-- · 2020-02-27 05:35
open(61,file='data.txt',action='write',position='append')
write(61,*) 'hey'
close(61)

This will append to an existing file, otherwise create and write. Adding status='unknown' would be equivalent.

查看更多
登录 后发表回答