开发者

How do I flush output to file after each write with a Fortran program?

I am running a loop in a Fortran program compiled with gfortran that outputs numerical values to an output file for each iteration of the loop. The problem is that the output is not saved to 开发者_开发知识库the file but every so many steps. How do I get it to flush each step?

Example code:

open(unit=1,file='output')

do i = 1, 1000
 write(1,*) i
end do

close(unit=1)


You need to make the output unbuffered. Try setting the GFORTRAN_UNBUFFERED_ALL environment variable to 'y', 'Y' or 1.


The other way, if gfortran implements it, is to call the non-standard subroutine flush. Not all compilers do implement this.


When I need to flush, I just close the file and reopen. This is clumsy and slow, but I don't know of a better way in fortran 90 that'll work with all compilers.


The suggestion from "user152979" was excellent and helpful - 10 years later! I'm using an MS-DOS Fortran 5.1 built prgm to transfer programs and data to a custom-made Z80 SBC (single-board computer). The thing is a little prototype, and has only serial ports. To make it work with an experimental Pentium MMX board, (which runs MS-DOS), I needed a little read-write program. Fortran fit the bill, and the .EXE fits on a diskette (no internet access on the MMX board). But the downloaded data to the Z80 was getting scrambled, if I wrote to the COM1 port.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜