Command-line arguments in main

Command-line arguments in main

Published by: Nuru

Published date: 21 Jun 2021

Command-line arguments in main Photo

Command-line arguments in main()

Accessing the command-line arguments is a very useful facility. It enables you to provide commands with arguments that the command can use e.g. the command

file prog.c

where the file is the command name, takes the argument "prog.c" and opens a file with that name, which it then displays.

  • The command-line arguments include the command name itself so that in the above example, "file" and "prog.c" are the command line arguments.
  • The first argument i.e. "file" is argument number zero, the next argument, "prog.c", is argument number one, and so on.
  • To access these arguments from within a C program, you pass parameters to the function main().
  • The use of arguments to main is a key feature of many C programs. The declaration of main looks like this:   int main (int argc, char *argv[])
  • This declaration states that main returns an integer value (used to determine if the program terminates successfully)
  • argc is the number of command-line arguments including the command itself i.e argc must be at least 1
  • argv is an array of the command line arguments
  • The declaration of argv means that it is an array of pointers to strings (the command-line arguments).
  • By the normal rules about arguments whose type is array, what actually gets passed to main is the address of the first element of the array.
  • As a result, an equivalent (and widely used) declaration is: int main (int argc, char **argv)

When the program starts, the following conditions hold true:

  1. argc is greater than 0.
  2. argv[argc] is a null pointer.
  3. argv[0], argv[1], ..., argv[argc-1] are pointers to strings with implementation-defined meanings.
  4. The argv[0] is a string that contains the program’s name or is an empty string if the name isn’t available.
  5. Remaining members of argv are the program’s arguments.

Example: print_args echoes its arguments to the standard output : form of echo command
/* print_args.c- Echo command-line arguments */
#include
#include
int main(int argc, char **argv)
{
int i = 0 ;
int num_args ;
num_args=argc;
printf("No of arguments: %d\n",num_args);
while(num_args > 0)
{
printf("%s\t", argv[i]);
i++ ;
num_args--;
}
}

If the name of this program is print_args, an example of its execution is as follows:
Run as:
C:\Users\Acer\Desktop\Programs>print_args aaa bbb ccc

Output as:
No of arguments: 4
print_args aaa bbb ccc