Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

stdout - Standard input and output units in Fortran 90?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a Fortran 2003 compiler, the intrinsic module iso_fortran_env defines the variables input_unit, output_unit and error_unit which point to standard in, standard out and standard error respectively.

I tend to use something like

#ifdef f2003
use, intrinsic :: iso_fortran_env, only : stdin=>input_unit, &
                                          stdout=>output_unit, &
                                          stderr=>error_unit
#else
#define stdin  5
#define stdout 6
#define stderr 0
#endif

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:

module iso_fortran_env

  ! Nonintrinsic version for Lahey/Fujitsu Fortran for Linux. 
  ! See Subclause 13.8.2 of the Fortran 2003 standard. 

  implicit NONE 
  public 

  integer, parameter :: Character_Storage_Size = 8 
  integer, parameter :: Error_Unit = 0 
  integer, parameter :: File_Storage_Size = 8 
  integer, parameter :: Input_Unit = 5 
  integer, parameter :: IOSTAT_END = -1 
  integer, parameter :: IOSTAT_EOR = -2 
  integer, parameter :: Numeric_Storage_Size = 32 
  integer, parameter :: Output_Unit = 6 

end module iso_fortran_env

As noted in other answers, 0, 5 and 6 are usually stderr, stdin and stdout (this is true for ifort on Linux) but this is not defined by the Fortran standard. Using the iso_fortran_env module is the correct way to portably write to these units.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...