2

I'm trying to pass arguments to a Fortran executable from the command line. A sample program that achieves this in C is (taken from here):

#include <stdio.h>

int main (int argc, char *argv[])
{
  int count;

  printf ("This program was called with \"%s\".\n",argv[0]);

  if (argc > 1)
    {
      for (count = 1; count < argc; count++)
    {
      printf("argv[%d] = %s\n", count, argv[count]);
    }
    }
  else
    {
      printf("The command had no other arguments.\n");
    }

  return 0;
}

The output of this program is:

This program was called with "./fubar".
argv[1] = a
argv[2] = b
argv[3] = c

My question now is, how would I code this program (and therefore this functionality) in Fortran? I have googled this, and it seems that only Fortran 2003 has the functionality of passing arguments to executables (is this correct)?

2
  • 1
    Sure, access to command line arguments was only standardised into Fortran 2003 but all the widely-used compilers have implemented the feature. You write as if it was 2004 or so. Try searching for 'fortran get command line arguments' Commented Nov 9, 2013 at 7:46
  • 1
    Thanks. I'm learning Fortran right now, so when I Google this stuff, it is sometimes not easy to judge the results. Your suggestion is very helpful though! Commented Nov 9, 2013 at 9:46

1 Answer 1

1

For future reference, as @High Performance Mark points out above, it is quite easy to do this in Fortran 2003. The below example code is taken from here and shows how:

      PROGRAM test_get_command_argument
        INTEGER :: i
        CHARACTER(len=32) :: arg

        i = 0
        DO
          CALL get_command_argument(i, arg)
          IF (LEN_TRIM(arg) == 0) EXIT

          WRITE (*,*) TRIM(arg)
          i = i+1
        END DO
      END PROGRAM
Sign up to request clarification or add additional context in comments.

3 Comments

cleaner to use..COMMAND_ARGUMENT_COUNT(). Why in the world the standards committee didn't just adopt the defacto standard getarg(),iargc() beats me..
sorry if that was too terse... i meant it would be better to use the arg count as the loop limit instead of using that if()exit construct
@george, no worries! This is how I learn from practitioners, i.e. you :-)! Thanks for pointing this out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.