Writing to standard output and writing to file are two different things, so you will always need separate instructions. But you don't have to open and close the file for every line you write.
Honestly, I don't think it's that much more of an effort:
open(unit=10, file='result.txt', status='replace', form='formatted')
....
write( *, *) "Here comes the data"
write(10, *) "Here comes the data"
....
write( *, *) root1, root2
write(10, *) root1, root2
....
close(10)
this is only one line more than what you would have to do anyway per write statement.
If you really think that you have too many write statements in your code, here are a few ideas that you might try:
If you are running on a Linux or Unix system (including MacOS), you can write a program that only writes to standard out, and pipe the output into a file, like this:
$ ./my_program | tee result.txt
This will both output the data to the screen, and write it into the file result.txt
Or you could write the output to a file in the program, and 'follow' the file externally:
$ ./my_program &
$ tail -f result.txt
I just had another idea: If you really often have the issue that you need to write data to both the screen and the file, you can place that into a subroutine:
program my_program
implicit none
real :: root1, root2, root3
....
open(10, 'result.txt', status='replace', form='formatted')
....
call write_output((/ root1, root2 /))
....
call write_output((/ root1, root2, root3 /))
....
call write_output((/ root1, root2 /))
....
close(10)
....
contains
subroutine write_output(a)
real, dimension(:), intent(in) :: a
write( *, *) a
write(10, *) a
end subroutine write_output
end program my_program
I am passing the values to be written here as an array because that gives you more flexibility in the number of variables that you might want to print. On the other hand, you can only use this subroutine to write real
values, for others (integer
, character
, etc) or combinations thereof you'd need to still have two write
statements, or write other specific 'write to both' routines.