Standard input and output units in Fortran 90? - fortran

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

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.

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.

It's actually 0 for stderr. 5 is stdin, 6 is stdout.
For example:
PROGRAM TEST
WRITE(0,*) "Error"
WRITE(6,*) "Good"
END PROGRAM TEST
Gives:
./a.out
Error
Good
while
./a.out 2> /dev/null
Good
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 standard way to write to stdout in Fortran is to put an asterisk instead of the unit number, i.e.,
WRITE(*,fmt) something
or to simply use
PRINT fmt,something
Similarly, the standard way to read from stdin is
READ(*,fmt) something
There is no standard way to write to stderr unless you use ERROR_UNIT from the ISO_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.

Related

What is the need for a C_INT fortran type? Are C and Fortran integers so different?

If I declare an integer in fortran as:
INTEGER(C_INT) :: i then, if I understand correctly, it's safe to be passed to a C function. Now disregarding the added headache of always declaring integers this way, is there any reasons not to always declare your variables as C-interoperable? Is there any downside to doing so?
Also, in the case of something as simple a an integer, what exactly does the C_INT change from a traditional Fortran integer? Are Fortran and C integers actually different?
The C integer size is usually fixed because the OS is compiled using C and the system bindings are published as C headers. The operating system designers choose one of the common models like LLP64, LP64, ILP64 (for 64-bit pointer OS's) and the C compilers then follow this choice.
But Fortran compilers are more free. You can set them to a different configuration. Fortran compiler set to use 8-byte default integers and 8-byte default reals are still perfectly standard conforming! (C would be as well but the choice is fixed in the operating system.)
And because the integers in C and in Fortran do not have to match you need a mechanism to portably select the C interoperable kind, whatever the default kind is.
This is not just academic. you can find libraries like MKL compiled with 8-byte integers (the ILP64 model, which is not used by common operating systems for C).
So when you call some API, some function whose interface is defined in C, you want to call it properly, not depending on the settings of the Fortran compiler. That is the use case for the C-interoperable types. If a C function requires an int, you give it an integer(c_int) and you do not care if the Fortran default integer is the same or not.
Basically there is no fundamental downside and on the same compiler there is no fundamental benefit.
Even in icc a long int is different on 32 and 64 bit OS, so you need to know (or define what you want on the c-side of things).
The only one that is clearly 4-bytes is the C_INT32_T, and hence it is that one that I generally use. And it more of a "future proofing" endeavour to use C_INT32_T , to define it as you want it to be in a fixed numbers of bits sizing.
These all give a 4 byte integer on iFort.
USE ISO_C_BINDING, ONLY : C_INT, C_INT32_T
Integer ::
INTEGER(KIND=4) :: !"B" At least on iFort
INTEGER*4 !"A"
INTEGER(KIND=C_INT) ::
INTEGER(KIND=C_INT32_T) :: !"C"
Usually one finds older code with the style of "A".
I routinely use the style of "B", but even though this is a "defacto standard" it is not conforming to "the standard".
Then when I become concerned with portability I run-through and change the "B" style to "C" style and then I have less heartburn considering others who may be later compiling with the gfortran compiler... Or even some other compiler.
The single byte:
BYTE :: !Good
INTEGER(KIND=1) ::
INTEGER(KIND=C_SIGNED_CHAR) ::
INTEGER(KIND=C_INT8_T) :: !Best
The two byte:
INTEGER(KIND=2) ::
INTEGER(KIND=C_INT16_T) :: !Best
INTEGER(KIND=C_SHORT) ::
The 8 byte:
INTEGER(KIND=8) ::
INTEGER(KIND=C_INT64_T) :: !Best
INTEGER(KIND=C_LONG_LONG) ::
While this looks somewhat fishy... One can also say:
LOGICAL(KIND=4) ::
LOGICAL(KIND=C_INT32_T) :: !Best here may be C_bool and using 1-byte logical in fortran...? Assuming that there is no benefit with the size of the logical being the same as some float vector
LOGICAL(KIND=C_FLOAT) ::

Is there an equivalent of DEXP for complex*16 arguments in Fortran?

As stated in the question : Is there an equivalent of DEXP for complex*16 arguments in Fortran (90 and later)?
complex*16 isn't Fortran (90 or earlier or later).
If your data type is complex(real64) (or the non-standard complex*16) the standard generic exp() will select the corresponding precision and range.
Where each part (Real and Imaginary) are 64 bits?
If you say COMPLEX(KIND=8) (intel) you get 64 bits for each the real and the imaginary. I'll need to see what gfortran gives...
It may best (I think most portable) to use ISO_C_BINDING and then 'see for yourself' :
PROGRAM ABC
USE ISO_C_BINDING
IMPLICIT NONE
COMPLEX(KIND=C_FLOAT_COMPLEX) :: A
COMPLEX(C_DOUBLE_COMPLEX) :: B
COMPLEX(C_LONG_DOUBLE_COMPLEX) :: C
WRITE(*,*) SIZEOF(A)=',SIZEOF(A)
WRITE(*,*) SIZEOF(B)=',SIZEOF(B)
WRITE(*,*) SIZEOF(C)=',SIZEOF(C)
END PROGRAM ABC
Since Fortran 77 there is very little reason to use DEXP() directly, unless you are passing it as an argument.
In normal expressions (the most common use by far, probably your case) just use the generic EXP() for all exponentiations.
If you have the rare case where DEXP() is passed as an argument to a function then no, there is no equivalent and you have to write a wrapper function which calls the generic EXP().
zexp() and cdexp() in GNU Fortran.
http://gcc.gnu.org/onlinedocs/gfortran/EXP.html

Code with syntax error in do loop compiles and gives wrong result

Here is the source (lets call it test4.F):
do 10 i=1
write(*,*) i
10 continue
end
With gfortran:
$gfortran test4.F
$./a.out
-259911288
with ifort:
$ifort test4.F
$./a.out
0
I know the syntax is incorrect. So both should throw compile-time errors.
Your test program is indeed not valid Fortran, but there isn't a syntax problem.
When the file has a .F suffix both gfortran and ifort assume that the program uses fixed form source. In fixed form source, blanks in statements aren't significant (outside character contexts). Your program is equivalent to:
do10i=1
write(*,*) i
10 continue
end
With comments:
do10i=1 ! Set the real variable do10i to value 1
write(*,*) i ! Write the undefined integer variable i
10 continue ! Do nothing
end ! End execution
Because of implicit typing you have a defaul real variable do10i and so there isn't a syntax error for a do control, and there isn't a do control that sets i to 1.
Instead your program is invalid because you are referencing the value of i although it hasn't first been defined (because it isn't a loop variable). But this isn't an error the compiler has to complain about at compile time (or even run time). A compiler is allowed to print any value it likes. gfortran chose one, ifort another.
Liberal use of implicit none and avoiding fixed-form source are good ways to avoid many programming errors. In this case, use of an end do instead of continue would also alert the compiler to the fact that you intended there to be some looping.
Which version of gfortran are you using? With gfortran-6, the following
PROGRAM MAIN
USE ISO_FORTRAN_ENV, ONLY:
1 COMPILER_VERSION,
2 COMPILER_OPTIONS
C EXPLICIT TYPING ONLY
IMPLICIT NONE
C VARIABLE DECLARATIONS
INTEGER I
DO 10 I = 1
WRITE (*,*) I
10 CONTINUE
PRINT '(/4A/)',
1 'THIS FILE WAS COMPILED USING ', COMPILER_VERSION(),
2 ' USING THE OPTIONS ', COMPILER_OPTIONS()
END PROGRAM MAIN
indeed throws the error
main.F:13:13:
DO 10 I = 1
1
Error: Symbol ‘do10i’ at (1) has no IMPLICIT type
I suspect that test4.F does not include the implicit none statement. Consequently, DO 10 I = 1 is interpreted as an implicitly defined real variable DO10I = 1. Here is a sample of a fixed form statement showing what are now (post Fortran 90) considered significant blanks followed by an equivalent statement without the blanks
DO I=1 , M AX ITER S
DO I = 1 , MAXITERS
Upshot, always use explicit variable declarations in all your programs. Better yet, only write Fortran in free source form main.f90. Free source form is more compatible with modern interactive input devices than fixed form. The maximum line length is 132 characters, compared to the older limit of 72 characters. This reduces the possibility of text exceeding the limit, which could lead the compiler to misinterpret names. Here's the same code in free source form
program main
use ISO_Fortran_env, only: &
stdout => OUTPUT_UNIT, &
compiler_version, &
compiler_options
! Explicit typing only
implicit none
! Variable declarations
integer :: i
do i = 1, 3
write (stdout, *) i
end do
print '(/4a/)', &
' This file was compiled using ', compiler_version(), &
' using the options ', compiler_options()
end program main
and
gfortran-6 -std=f2008ts -o main.exe main.f90
./main.exe
yields
1
2
3
This file was compiled using GCC version 6.1.1 20160802 using the options -mtune=generic -march=x86-64 -std=f2008ts

Using underscores to define kind/precision

I've been using using an underscore to define an integer as a specific kind in fortran.
Here is a snippet of code to demonstrate what 1_8 means, for example:
program main
implicit none
integer(2) :: tiny
integer(4) :: short
integer(8) :: long
tiny = 1
short = 1
long = 1
print*, huge(tiny)
print*, huge(1_2)
print*, huge(short)
print*, huge(1_4)
print*, huge(long)
print*, huge(1_8)
end program main
Which returns (with PGI or gfortran):
32767
32767
2147483647
2147483647
9223372036854775807
9223372036854775807
I'm using the huge intrinsic function to return largest number of the given kind. So 1_8 is clearly the same kind as integer(8). This works for real numbers also, although I haven't shown it here.
However, I've been unable to find any documentation of this functionality and I don't remember where I learned it. My question is:
Is using _KIND standard fortran? Does anybody have a source for this?
Edit: It's been pointed out that the kind values I've used (2,4,8) are not portable - different compilers/machines may give different values for huge(1_4), for example.
It is standard Fortran, as of Fortran 90, though the set of valid kind values for each type and the meaning of a kind value is processor dependent.
The Fortran standard is the definitive source for what is "standard" Fortran. ISO/IEC 1539-1:2010 is the current edition, which you can buy, or pre-publication drafts of that document are available from various places. https://gcc.gnu.org/wiki/GFortranStandards has a collection of useful links.
I would expect that many compiler manuals (e.g - see section 2.2 of the current PGI Fortran reference manual) and all reasonable textbooks on modern Fortran would also describe this feature.
As already answered, this notation is standard fortran, but using these specific numeric values for kinds is not portable. Previous answers have described compilers that use other schemes. There are several other approaches that are portable.
First, use the kind scheme to define symbols, then use those symbols for numeric constants:
integer, parameter :: RegInt_K = selected_int_kind (8)
write (*, *) huge (1_RegInt_K)
Or use the kind definitions that are provided in the ISO_FORTRAN_ENV module, e.g.,
write (*, *) huge (1_int32)
The kinds of this module are specified in the number of bits used for storage. Some of the kinds are only available with Fortran 2008. If those are missing in your compiler, you can use the kind definitions provided with the ISO_C_BINDING, which is older.
To add to IanH's answer the specification for an integer literal constant in Fortran 2008 is given in 4.4.2.2. Something like 1_8 fits in with R407 and R408 (for the obvious digit-string):
int-literal-constant is digit-string [_kind-param]
kind-param is digit-string or scalar-int-constant-name
You can find similar for other data types (although note that for characters the kind parameter is at the front of the literal constant).

Scientific notation in namelist with gfortran

I want to load a list from an input file via a namelist. To compile, I use gfortran:
PROGRAM main
IMPLICIT NONE
INTEGER :: val,err
NAMELIST /myNamelist/ val
OPEN(100,file='input.txt')
READ(unit=100,nml=myNamelist,iostat=err)
CLOSE(100)
PRINT *, val
END PROGRAM
The input.txt looks like the following:
&myNamelist
val = 3e3
/
The program prints a 0 instead of 3000. If I plug in val = 3000 in the input file, it works. It seems that gfortran does not support scientific notation in a namelist. With ifort however it runs fine. Is there a workaround or something to use scientific notation in a namelist with gfortran?
You use iostat=err, but you do not check the value of err! If you did that you would found out that an error condition happened and err is nonzero. Therefore, val is of no use.
The scientific notation is not valid for integer input. Either read a real variable or do not use the scientific notation.
Try:
PROGRAM main
IMPLICIT NONE
INTEGER :: val,err
character(256) :: msg
NAMELIST /myNamelist/ val
OPEN(100,file='input.txt')
READ(unit=100,nml=myNamelist,iostat=err,iomsg=msg)
CLOSE(100)
PRINT *, err
PRINT *, msg
print *, val
END PROGRAM
run:
> sunf90 intnml.f90
> ./a.out
1083
unexpected character in integer value
0
BTW, Intel Fortran accepts the value, but that is a non-standard extension. Your program would be non-portable if you relied on that.
The draft of the 2008 standard that I have to hand states, at para 10.11.3.3.6, in the context of reading name lists:
When the next effective item is of type integer, the value in the input
record is interpreted as if an Iw edit descriptor with a suitable
value of w were used.
In this case gfortran is doing no more than the standard requires while the Intel compiler goes a bit further and implements an extension that copes with a non-standard form of an integer value, ie 3e3.