Where command line arguments are supported they can be read in via the get_command_argument
intrinsic (introduced in the Fortran 2003 standard). The command_argument_count
intrinsic provides a way to know the number of arguments provided at the command line.
All command-line arguments are read in as strings, so an internal type conversion must be done for numeric data. As an example, this simple code sums the two numbers provided at the command line:
PROGRAM cmdlnsum
IMPLICIT NONE
CHARACTER(100) :: num1char
CHARACTER(100) :: num2char
REAL :: num1
REAL :: num2
REAL :: numsum
!First, make sure the right number of inputs have been provided
IF(COMMAND_ARGUMENT_COUNT().NE.2)THEN
WRITE(*,*)'ERROR, TWO COMMAND-LINE ARGUMENTS REQUIRED, STOPPING'
STOP
ENDIF
CALL GET_COMMAND_ARGUMENT(1,num1char) !first, read in the two values
CALL GET_COMMAND_ARGUMENT(2,num2char)
READ(num1char,*)num1 !then, convert them to REALs
READ(num2char,*)num2
numsum=num1+num2 !sum numbers
WRITE(*,*)numsum !write out value
END PROGRAM
The number argument in get_command_argument
usefully ranges between 0
and the result of command_argument_count
. If the value is 0
then the command name is supplied (if supported).
Many compilers also offer non-standard intrinsics (such as getarg
) to access command line arguments. As these are non-standard, the corresponding compiler documentation should be consulted.
Use of get_command_argument
may be extended beyond the above example with the length
and status
arguments. For example, with
character(5) arg
integer stat
call get_command_argument(number=1, value=arg, status=stat)
the value of stat
will be -1
if the first argument exists and has length greater than 5. If there is some other difficulty retrieving the argument the value of stat
will be some positive number (and arg
will consist entirely of blanks). Otherwise its value will be 0
.
The length
argument may be combined with a deferred length character variable, such as in the following example.
character(:), allocatable :: arg
integer arglen, stat
call get_command_argument(number=1, length=arglen) ! Assume for simplicity success
allocate (character(arglen) :: arg)
call get_command_argument(number=1, value=arg, status=stat)