Command-line interface#
- command-line interface
a means of interacting with software via commands. Also called command-line shell.
main arguments#
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
for (size_t i = 0; i < argc; ++i)
puts(argv[i]);
}
$ code-wi/main-arguments.exe geko --1 🦎
code-wi/main-arguments.exe
geko
--1
🦎
Three arguments are provided to main-arguments.exe. But why do we see 4 lines that are printed?
Activity 33 (Basic CLI)
Create a program that accepts any number of words as arguments and prints them back as a single, space-separated string in reverse order (last argument printed first), but only if the verb is reverse. Otherwise it prints usage:
$ ./main reverse a b c
c b a
$ ./main a b c
Usage: ./main reverse STRING1 STRING2 ...
Exit status#
If main returns, then the program exits. The program can communicate a status to the command line interface by returning a corresponding integer called exit status.
- exit status
an integer returned by a terminated program that is made available to its caller, e.g., the command line interface.
Every function with a return type other than void must return a value. However, main is special. If no return value is not specified, it returns automatically return 0:
int main() {}
exit code |
meaning |
|---|---|
|
successful termination |
|
unsuccessful termination |
any |
unsuccessful termination with a special meaning |
CLI design#
Here are good examples for CLI programs.
VS Code considerations#
You cannot use F5 directly, because our program’s runtime is now dependent on arguments. There are two solutions:
Only build using CtrlShiftb. Then run manually on the command line:
./main e caesar LEVE
You change
launch.jsonto cater for command-line arguments, e.g.,{ "version": "0.2.0", "configurations": [ { // ... "program": "${workspaceFolder}/main", "args": [ "${input:verb}", "${input:cipher}", "${input:plaintext}" ], // ... } ], "inputs": [ { "id": "verb", "type": "promptString", "description": "Enter verb" }, // ... ]