C
getopt
Learn option processing with getopt.
Options with getopt
getopt is a standard POSIX function that parses command-line options such as -v or -n foo. It is declared in <unistd.h>.
Call it as int opt; while ((opt = getopt(argc, argv, "vn:")) != -1). Here "vn:" is the option string: v is a single-letter flag, n: with its trailing colon means n takes an argument. That argument is available through the optarg global. When all options are scanned, getopt returns -1 and the loop ends.
Handling options with switch
The body of the getopt loop usually holds a switch block. Each case corresponds to one option letter and performs the matching action.
Example: case 'v': printf("verbose\n"); break; and case 'n': printf("name=%s\n", optarg); break;. The default arm catches unknown options and typically prints a usage message. Each arm must end with break; otherwise control falls through to the next arm. This structure is the heart of option handling in real UNIX tools.
Exercise Write a getopt loop
Add #include <unistd.h>. Declare int opt; and set up while ((opt = getopt(argc, argv, "vn:")) != -1). In a switch (opt) add case 'v': with printf("ayrıntılı\n"); break; and case 'n': with printf("isim=%s\n", optarg); break;. After the loop add printf("tamam\n");.
Show example solution
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "vn:")) != -1) {
switch (opt) {
case 'v':
printf("ayrıntılı\n");
break;
case 'n':
printf("isim=%s\n", optarg);
break;
}
}
printf("tamam\n");
return 0;
}
Test yourself
-
Complete the getopt call
while ((opt = getopt(argc, argv, "____")) != -1)
Show answer
while ((opt = getopt(argc, argv, "vn:")) != -1)
-
Match the getopt parts
- getopt
- Option parser
- optarg
- Argument value
- vn:
- Option string
- -1
- Scan finished
-
What does optarg hold?
- The option count
- The program name
- The value of an option that takes an argument
- An error code
Show answer
The value of an option that takes an argument — optarg holds the argument value for options marked with a colon (e.g. n:).
Next lesson: Argument validation