How to Read Program Arguments in C

In C program arguments are part of the main method signature.


int main ( int argc, char *argv[] )

This means that you can read a specific argument by reading the nth index of the argv array. The classic hello world program with arguments is thus this easy:

#include <stdio.h>
int main (int argc, char *argv[])
{
  if ( argc < 2 )
  {
      printf( "usage: %s name [name]&nbsp;[name] [name]", argv[0] );
  }
  // we start from 1 since the zero index is the program name
  for(int i=1;i<argc;i++) {
    printf( "Hello %s\n", argv[i] );
  }
  return 0;
}

Compile the program using gcc test.c -o test and run the program with any number of arguments.

./test one two "Claus Witt"

Output:

Hello one
Hello two
Hello Claus Witt

Related Posts