I would like to know if in Fortran it is possible to use just a single command (with options/specifiers) to do the following:
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)
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.
You can use cat with redirection to append a file to another file. You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
Use the echo command, used with the append redirection operator, to add a single line of text to a file. This adds the message Remember to back up mail files by end of week. to the end of the file notes.
To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.
open (unit = number, file = "name") . open (unit = 24, file = "c:\\fortran\\data\\divisors. dat") . Fortran uses the unit number to access the file with later read and write statements.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With