Command Line Arguments
When executing a program, values can be passed to a C program from the command line. These values are called command line arguments and they are crucial for the program, especially when you want to control the program externally rather than hardcoding these values within the code.
Command line arguments are handled using the main() function parameters, where argc represents the number of arguments passed, and argv[] is an array of pointers to each argument passed to the program. Below is a simple example that checks if any arguments are provided from the command line and performs actions based on the arguments:
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc == 2)
{
printf("The argument supplied is %s\n", argv[1]);
}
else if(argc > 2)
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
Compiling and executing the above code with one argument produces the following result:
$./a.out testing
The argument supplied is testing
Compiling and executing the above code with two arguments produces the following result:
$./a.out testing1 testing2
Too many arguments supplied.
Compiling and executing the above code without any arguments produces the following result:
$./a.out
One argument expected
It should be noted that argv[0] stores the program's name, argv[1] is a pointer to the first command line argument, and *argv[n] is the last argument. If no arguments are provided, argc will be 1; otherwise, if one argument is passed, argc will be set to 2.
Multiple command line arguments are separated by spaces, but if the argument itself contains spaces, the argument should be enclosed in double quotes "" or single quotes ''. Let's rewrite the above example to pass a command line argument enclosed in double quotes:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Program name %s\n", argv[0]);
if(argc == 2)
{
printf("The argument supplied is %s\n", argv[1]);
}
else if(argc > 2)
{
printf("Too many arguments supplied.\n", argv[1]);
}
else
{
printf("One argument expected.\n");
}
}
Compiling and executing the above code with a simple argument separated by spaces and enclosed in double quotes produces the following result:
$./a.out "testing1 testing2"
Program name ./a.out
The argument supplied is testing1 testing2