Command line arguments are referred to parameters that are passed to a program when it is to be executed via the command line/terminal.
We can pass command line arguments to a C program by adding individual arguments separated by spaces after the command to execute the binary file.
Below is the syntax that shows how to pass command line arguments to a C program.
./<programName> <argument1> <argument2> ...
The programName
is the name of the binary executable file, while argument1
and argument2
refer to the two arguments we pass to the program.
Let's say we have a C program named passArguments
. We will use the command ./passArguments
in the command line to run the program.
If we want to pass two arguments, arg1
and arg2
, to the program, we will add them after the program's name, separated by spaces.
So our shell command would be:
./passArguments arg1 arg2
We will now examine how we can access those arguments within the program. To retrieve the command line arguments, we have two parameters that we can pass to the main()
function.
argc
: This integer variable refers to the number of arguments passed to the program via the command line.
argv
: This refers to the argument vector, an array of strings containing the arguments passed to the program.
Below, we can see how to initialize these parameters in the main()
function.
int main(int argc, char* argv[]){// write code here}
All arguments will be stored in the double-pointer char array named argv
, with the number of arguments inside argc
.
We will now look at the C program below, which prints all the arguments passed to the program via the command line.
#include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]){ for(int i = 0; i < argc; i++){ printf("\nArgument %d = argv[%d] = %s\n", i , i, argv[i]); } return 0; }
Note: To pass custom arguments to the program, click the "Run" button and in the terminal, use the command
./args arg1 arg2 ...
wherearg1
andarg2
are the command line arguments.
Lines 4–11: We declare the main
function, passing argc
, and argv
to access the command line arguments.
Lines 6–8: We use a for
loop that starts from 0 and goes on till the number of arguments given to the program accessed via the argc
variable.
Line 7: We print each command line argument by accessing each element from the argv
array.
Try to see if you can solve the problem statement below.
Problem statement
Suppose we have coded the C program that is shown below. We compiled it and named its binary file display_args
.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
printf("%s", argv[0]);
return 0;
}
What will the code output be when we run the command ./display_args arg1 arg2
?
Nothing
./display_args
arg1
arg2
Free Resources