在一行中打印和写入?
Print and write in one line?
是否可以在屏幕上打印一些东西,同时将打印的内容也写入文件中?
现在,我有这样的东西:
print *, root1, root2
open(unit=10,file='result.txt'
write(10,*), root1, root2
close(10)
我觉得我在浪费代码,让代码变得比应有的更长。我实际上想要 print/write 比这些多得多的行,所以这就是为什么我正在寻找一种更简洁的方法来做到这一点。
写入标准输出和写入文件是两件不同的事情,因此您总是需要单独的指令。但是你不必为你写的每一行打开和关闭文件。
老实说,我不认为这需要更多的努力:
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)
这只比您在每个写入语句中必须执行的操作多一行。
如果你真的认为你的代码中有太多的写语句,这里有一些你可以尝试的想法:
如果你 运行 在 Linux 或 Unix 系统(包括 MacOS)上,你可以编写一个只写入标准输出的程序,然后将输出通过管道传输到一个文件中,就像这样:
$ ./my_program | tee result.txt
这会将数据输出到屏幕,并将其写入文件result.txt
或者您可以将输出写入程序中的文件,然后 'follow' 外部文件:
$ ./my_program &
$ tail -f result.txt
我有另一个想法:如果你真的经常遇到需要将数据写入屏幕和文件的问题,你可以将其放入子程序中:
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
我将要在此处写入的值作为数组传递,因为这使您可以更灵活地选择可能要打印的变量数量。另一方面,您只能使用此子例程来编写 real
值,对于其他值(integer
、character
等)或其组合,您仍然需要有两个 write
语句,或编写其他特定的 'write to both' 例程。
是否可以在屏幕上打印一些东西,同时将打印的内容也写入文件中? 现在,我有这样的东西:
print *, root1, root2
open(unit=10,file='result.txt'
write(10,*), root1, root2
close(10)
我觉得我在浪费代码,让代码变得比应有的更长。我实际上想要 print/write 比这些多得多的行,所以这就是为什么我正在寻找一种更简洁的方法来做到这一点。
写入标准输出和写入文件是两件不同的事情,因此您总是需要单独的指令。但是你不必为你写的每一行打开和关闭文件。
老实说,我不认为这需要更多的努力:
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)
这只比您在每个写入语句中必须执行的操作多一行。 如果你真的认为你的代码中有太多的写语句,这里有一些你可以尝试的想法:
如果你 运行 在 Linux 或 Unix 系统(包括 MacOS)上,你可以编写一个只写入标准输出的程序,然后将输出通过管道传输到一个文件中,就像这样:
$ ./my_program | tee result.txt
这会将数据输出到屏幕,并将其写入文件result.txt
或者您可以将输出写入程序中的文件,然后 'follow' 外部文件:
$ ./my_program &
$ tail -f result.txt
我有另一个想法:如果你真的经常遇到需要将数据写入屏幕和文件的问题,你可以将其放入子程序中:
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
我将要在此处写入的值作为数组传递,因为这使您可以更灵活地选择可能要打印的变量数量。另一方面,您只能使用此子例程来编写 real
值,对于其他值(integer
、character
等)或其组合,您仍然需要有两个 write
语句,或编写其他特定的 'write to both' 例程。