Building a CLI Tool
Practical example.
Putting it together
Now we combine arguments, options, and parsing into a small but complete CLI tool.
Our example is a number-formatting utility that reads a value and a few options, then prints a result.
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
printf("You passed: %s\n", argv[1]);
return 0;
}Designing the interface
Good CLI tools define their interface up front. Ours will accept:
-vverbose output-r Nrepeat the output N times- one positional argument: the text to print
#include <stdio.h>
int main(void) {
printf("Interface: prog [-v] [-r N] <text>\n");
return 0;
}All lessons in this course
- argc and argv
- Parsing Options
- getopt
- Building a CLI Tool