We can use C in order to create command line interface (CLI) tools. These are tools whose main mode of interaction is characterized by the user inputting commands (usually in the format verb adverb1 adverb2 …).
Passing CLI arguments
The main function can be used without passing any arguments into it but it can also be used in a certain way in order to access the arguments passed into the program via the command line:
int main(int argc,char** argv){
return 0;
}
argc is the argument count (the number of arguments passed via the command line) and argv is a vector (a list of strings), with each string corresponding to an argument.
The first argument
The first argument (argv[0]) is always the path to the program:
#include <stdio.h>
int main(int argc, char **argv){
printf("This program is located at %s\n",argv[0]);
return 0;
}
Listing the arguments example
We can use a for loop and the argument count argc in order to loop over the various arguments (argv[0], argv[1], argv[2], …, argv[argc-1]):
#include <stdio.h>
int main(int argc, char **argv){
for (int i=0;i<argc;i++){
printf("Argument %d: %s\n",i+1,argv[i]);
}
return 0;
}
Compile this program to produce an executable called ’list':
gcc cli-list-arguments.c -o list
Now in your terminal type:
./list hello there
Addition example
Let’s make an addition tool for the command line:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
if (argc==1){
// do nothing because the only argument is the program path
printf("Please pass some numbers into the program!\n");
return -1;
}
int sum = 0;
// start iteration at i=1 to skip the program path argument (at argv[0])
for (int i=1;i<argc;i++){
// convert a string into an integer
int num = atoi(argv[i]);
printf("Adding number: %d\n",num);
sum+=num;
}
printf("Sum: %d\n",sum);
return 0;
}
The atoi function is defined in the stdlib.h header file and is used to convert a string to an integer. This is necessary as each argument passed from the command line is a string and the computer would not know if a number is to be treated as an integer or a string of numerical digits.
Compile this program to produce an executable called ‘add’:
gcc cli-addition.c -o add
Now in your terminal type:
./add 4 9 1
You can add these programs to path so you can run them from anywhere in your file system:
list hello there
add 4 9 1