我在 Fortran 90 程序中运行一个循环,该程序为循环的每次迭代将数值输出到输出文件。问题是输出没有保存到文件中,而是每隔这么多步骤。我如何让它冲洗每一步?
示例代码:
open(unit=1,file='output')
do i = 1, 1000
write(1,*) i
end do
close(unit=1)
提前致谢。
您需要使输出无缓冲。尝试将GFORTRAN_UNBUFFERED_ALL环境变量设置为“y”、“Y”或 1。
另一种方式,如果 gfortran 实现它,就是调用非标准子例程 flush。并非所有编译器都实现了这一点。
当我需要刷新时,我只需关闭文件并重新打开。这既笨拙又慢,但我不知道在 fortran 90 中有更好的方法可以与所有编译器一起使用。
“user152979”的建议非常好而且很有帮助——10 年后!我正在使用 MS-DOS Fortran 5.1 构建的 prgm 将程序和数据传输到定制的 Z80 SBC(单板计算机)。这个东西是一个小原型,只有串口。为了使它与一个实验性的 Pentium MMX 板(运行 MS-DOS)一起工作,我需要一个小的读写程序。Fortran 符合要求,.EXE 适合放在软盘上(MMX 板上没有 Internet 访问权限)。但是,如果我写到 COM1 端口,下载到 Z80 的数据就会被打乱。
Turns out Fortran was buffering the data. I was only getting part of about every 10th record at the Z80. Closing the COM1 file (the output device) and reopening after writing each record of text, caused the buffer to be flushed, and the little Fortran downloader (and the Z80 SBC) now work perfectly.
So, even if your version of Fortran does not support a "FLUSH" operator, closing and immediately re-opening the file worked fine to flush the buffer contents to the device.
A Side Note about using DOS to write to COM1 port: I had to strap serial port RS-232c pins CTS to pins DTR, DCD and DSR so that MS-DOS could "see" and write to the serial port. In later versions of MS-DOS (ie. "Windows"), you can use the MODE command to set COM port RTS and CTS values to OFF, but with original DOS, you need to use a soldering iron. AND you need to flush any buffered data, after each record write. User152979 says this close & re-open is "clumsy and slow", but in my case, this trick worked perfectly.