Version 4 (modified by 12 years ago) ( diff ) | ,
---|
Command-Line Arguments in FORTRAN
Note: this assumes the user has at least FORTRAN 90.
In the vast majority of cases, creating a namelist data file will be faster and easier. Still, you might like to make a command-line fortran program for sheer novelty's sake. Fortran treats all arguments as characters.
The main functionality comes from two commands, IARGC()
and GETARG()
.
nargs=IARGC()
:IARGC()
is an integer function that returns the number of arguments supplied to the program. A count of 0 means none were supplied.
GETARG(iarg,argchar)
: The subroutineGETARG
has two arguments. The first is an integer specifying which command-line argument to return, and the second is a character string to be filled with the argument. Asking for argument 0 will return the program name.
So, we can figure out how many arguments were passed, and we can put them all into strings. What if we want to pass, say, how many iterations to do something? This requires converting the character strings to, say, integers.
Converting Strings to Integers
The way Fortran handles this is wack. From GFortran documentation, the way to do it is to READ the string into an integer,
character(LEN=10) :: string integer :: ival string='154' READ(string,'(I)')ival
Note that trying to WRITE to an integer doesn't work. Attempting something like
WRITE(ival,'(I)')string
produces a fatal "forrtl: severe (61): format/variable-type mismatch
." Changing the format code,
WRITE(ival,'(A)')string
does not produce an error, but also does nothing to ival
.
Note: Presumably this is how you would convert strings to floats, but I haven't tried it.
Converting Integers to Strings
In contrast, the way to convert from integer to character is with a WRITE statement,
WRITE(string,'(I10)')ival