Search code examples
fortrangfortranflushcarriage-return

How to carriage return and flush in Fortran?


I've always wondered about whether or not you can carriage return and flush a write statement in Fortran. In Python/C++ you can '/r' then flush the stream.

How can I do this in Fortran?


Solution

  • A carriage-return is inserted by default at the end of a write statement, or explicitly using the ADVANCE specifier:

    write(unit , '(A)') 'Hello World'
    write(unit , '(A)' , ADVANCE = 'YES') 'Hello World'
    write(unit , '(A)' , ADVANCE = 'YES') '-'
    

    The result of the preceding three statements is:

    Hello World
    Hello World
    -
    

    Alternatively, the carriage-return may be suppressed by specifying ADVANCE='NO':

    write(unit , '(A)' , ADVANCE = 'NO') 'Hello World'
    write(unit , '(A)' , ADVANCE = 'NO') 'Hello World'
    write(unit , '(A)' , ADVANCE = 'NO') '-'
    

    Which yields:

    Hello WorldHello World-
    

    To flush in Fortran90, close the file and reopen. Specific compilers and/or newer versions of the Fortran standard offer FLUSH as an intrinsic, but closing the file will always have the effect of flushing regardless of your Fortran version.