Summary - Command line
- C course
- Intermediate
- Lesson 93/116
- 5 min
Combine argc, getopt and exit to write a CLI tool.
Designing a command handler
In this summary you'll combine argc/argv, getopt and exit to write a command handler. The handler walks a fixed command list and prints each one.
The structure: define a command array, loop over each with for, and print with printf. Finally end with printf("Tamamlandı\n");. This is the skeleton of real CLI tools: take arguments, process, print, return an exit code. Because the command count is fixed the output is always the same, making testing easy.
Practice Write a command handler
Declare char *cmds[] = {"yardım", "çalıştır", "çık"}; and int n = 3;. Loop with for (int i = 0; i < n; i++) and print each command with printf("Komut: %s\n", cmds[i]);. After the loop print printf("Tamamlandı\n");.
Starter code
#include <stdio.h>
// Define the cmds array and the count n
// Loop over each command and print it
// Print "Tamamlandı"
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
char *cmds[] = {"yardım", "çalıştır", "çık"};
int n = 3;
for (int i = 0; i < n; i++) {
printf("Komut: %s\n", cmds[i]);
}
printf("Tamamlandı\n");
return 0;
}Expected output
Komut: yardım Komut: çalıştır Komut: çık Tamamlandı
Summary
In this group you learned command-line arguments in depth. You saw taking input with argc and argv, looping over them, parsing options with getopt, argument validation, and exit codes with exit.
You combined these to write a command handler skeleton. Real CLI tools follow the same flow: take, parse, validate, process, print, exit. In the next groups these foundations will be used on debugging and bitwise operations. Command-line skill is essential in systems programming; every tool eventually offers a CLI.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In what order does a CLI tool skeleton run?
- Print, take, process, exit
- Exit, take, process, print
- Take, process, print, exit Correct answer
- Process, exit, take, print
Explanation: A CLI tool takes arguments, processes, prints, then exits.
2 Match concepts to use
| Term | Meaning |
|---|---|
argc/argv |
Taking arguments |
getopt |
Option parsing |
exit |
Exit code |
printf |
Printing results |