Command Line Arguments
- Getting the arguments from command prompt in c is known as command line arguments.
- Command line is that it consists of a sequence of words,typically separated by space. Main program can receive these words as an array of strings,one word per string.
- main function will accept 2 parameters ,argv and argc
- argc will be the count of the number of strings given on the command line.
- argv will be the array of the arguments.since each word is a string argv is an array of pointers to char
- Example:
int main(int argc,char *argv[]){statements to be executed} - The strings at the command line are stored in memory and address of the first string is stored in argv[0],address of the second string is stored in argv[1] and so on.
- we can give any name instead of argv and argc
Example:
main(int count,char*str[]){…..} - Example Program
#include<stdio.h>
int main(int argc,char *argv[])
{
int i;
printf(“Number of Arguments passed=%d\n”,argc);
for(i=0;i<argc;i++)
printf(“argv[%d]=%s\n”,i,argv[i]);
return;
}
Output
emblogic@host:~/$ ./a.out g h k
Number of Arguments passed=4
argv[0]=./a.out
argv[1]=g
argv[2]=h
argv[3]=k
Command Line Arguments in Unix/Linux:
- Most Unix/Linux applications lets the user to specify command-line arguments (parameters) in 2 forms* Short options
consist of a – character followed by a single alphanumeric character
for example for listing the files the command is ls -l
* Long options (common in GNU applications)
consists of two – characters (–) followed by a string made up of letters, numbers, and hyphens. - Either type of option may be followed by an argument.
- A space separates a short option from its arguments
- Either a space or an = separates a long option from an argument.
- GNU C provides 2 functions, getopt and getopt_long() to parse the command line args specified in the above format
- getopt – supports parsing only short options
- getopt_long – supports parsing of both short and long options.
getopt_long()
- This function is defined in getopt.hSyntax:
——-
int *getopt_long* (int argc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)Usage:
——
while (getopt_long (argc, argv, shortopts, longopts, index) != -1) {
}Parameters
———-
argc and argv are the command line args passed to main
shortopts: This is a string containing all the valid short option characters An option character can be followed by
a colon (:) to indicate that it takes a required argument. (or)
2 colon (::) to indicate that its argument is optional shortopts can begin with a + to indicate that getopts_long should stop processing on sensing an unexpected arg
Ex: If we have have a program that can accept the short args -a and -b, the option string would be “ab”Now, if we have to force a mandatory required parameter for -a, but not for -b, the option string would be “a:b::”