Command Line Arguments in Fortran
Command-line arguments are a common way to parameterize execution of programs. For example, ./my_program arg1 arg2
uses arg1
and arg2
as arguments to the my_program
executable.
program command_line_arguments
use, intrinsic :: iso_fortran_env, only: output_unit
implicit none
integer :: num_args, i
character(len=100), dimension(:), allocatable :: args
! Get the number of command-line arguments
num_args = command_argument_count()
! Allocate an array to store the arguments
allocate(args(0:num_args))
! Get the program name (equivalent to args[0] in some languages)
call get_command_argument(0, args(0))
! Get the command-line arguments
do i = 1, num_args
call get_command_argument(i, args(i))
end do
! Print all arguments including the program name
write(output_unit,*) "All arguments (including program name):", args
! Print arguments without the program name
write(output_unit,*) "Arguments without program name:", args(1:)
! Print a specific argument (if available)
if (num_args >= 3) then
write(output_unit,*) "Third argument:", args(3)
end if
! Deallocate the array
deallocate(args)
end program command_line_arguments
In Fortran, we use the intrinsic procedures command_argument_count()
and get_command_argument()
to access command-line arguments. The first argument (index 0) is typically the program name, similar to other languages.
To experiment with command-line arguments, it’s best to compile the program first:
$ gfortran command_line_arguments.f90 -o command_line_arguments
$ ./command_line_arguments a b c d
All arguments (including program name):./command_line_arguments a b c d
Arguments without program name:a b c d
Third argument:c
In this example, we’ve demonstrated how to access all arguments, arguments without the program name, and how to access a specific argument by index.
Next, we’ll look at more advanced command-line processing with options parsing libraries available in Fortran.