How can I read and write to the standard input, output and error streams stdin
, stdout
and stderr
in Fortran? I've heard writing to stderr
, for example, used to be write(5, fmt=...)
, with 5
the unit for stderr
, and I know the way to write to stdout
is to use write(*, fmt=...)
.
How do I read and write to the standard input and output units with the ifort
compiler?
Compiler version:
Intel(R) Fortran Compiler for applications running on Intel(R) 64, Version 10.0 Build 20070426 Package ID: l_fc_p_10.0.023 Copyright (C) 1985-2007 Intel Corporation. All rights reserved
It's actually 0 for stderr. 5 is stdin, 6 is stdout.
For example:
Gives:
while
I would store a PARAMETER that is STDERR = 0 to make it portable, so if you hit a platform that is different you can just change the parameter.
This example was compiled and run with ifort 12.1.1.256, 11.1.069, 11.1.072 and 11.1.073.
The Fortran standard doesn't specify which units numbers correspond to stdin/out/err. The usual convention, followed by e.g. gfortran, is that stderr=0, stdin=5, stdout=6.
If your compiler supports the F2003 ISO_FORTRAN_ENV intrinsic module, that module contains the constants INPUT_UNIT, OUTPUT_UNIT, and ERROR_UNIT allowing the programmer to portably retrieve the unit numbers for the preconnected units.
If you have a Fortran 2003 compiler, the intrinsic module
iso_fortran_env
defines the variablesinput_unit
,output_unit
anderror_unit
which point to standard in, standard out and standard error respectively.I tend to use something like
in my input/output routines. Although this of course means preprocessing your source file (to do this with
ifort
, use the-fpp
flag when compiling your source code or change the source file extension from.f
to.F
or from.f90
to.F90
).An alternative to this would be to write your own, non-intrinsic,
iso_fortran_env
module (if you don't have a Fortran 2003 compiler), as discussed here(this link has died since this answer was posted). In this example they use a module:As noted in other answers, 0, 5 and 6 are usually
stderr
,stdin
andstdout
(this is true forifort
on Linux) but this is not defined by the Fortran standard. Using theiso_fortran_env
module is the correct way to portably write to these units.The standard way to write to
stdout
in Fortran is to put an asterisk instead of the unit number, i.e.,or to simply use
Similarly, the standard way to read from
stdin
isThere is no standard way to write to
stderr
unless you useERROR_UNIT
from theISO_FORTRAN_ENV
module, which requires Fortran 2003 or later.Unit numbers 0, 5 and 6 will certainly work in the
ifort
compiler (and also in some other Fortran compilers), but keep in mind they are compiler-dependent.