打印并写入一行?

时间:2015-05-07 02:56:24

标签: file-io fortran

是否可以在屏幕上打印某些内容,同时还可以将正在打印的内容写入文件中? 现在,我有这样的事情:

var str= "always on the go? if yes, slip-on this dress that comes with u-         neck,long sleeves and loose fit. wear with slacks and beanie to finish the ensemble.↵↵- u-neck↵- long sleeves↵- loose fit↵- knee hemline↵- plain print".

var arr= str. split(/([^\.,?\n]+[\.,?\n])/gi);

我觉得我在浪费行,并且使代码变得更长。我实际上想要打印/写出更多这些线条,所以这就是为什么我正在寻找一种更清晰的方法。

1 个答案:

答案 0 :(得分:7)

写入标准输出和写入文件是两回事,所以你总是需要单独的指令。但是,您不必为您编写的每一行打开和关闭文件。

老实说,我认为这不仅仅是一种努力:

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

或者您可以将输出写入程序中的文件,然后按照'外部文件:

$ ./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值,而其他人(integercharacter等)或其组合您需要还有两个值write语句,或写其他特定的'写入'例程。