CodeBlanks Logo Icon CodeBlanks

getopt

  • C course
  • Intermediate
  • Lesson 90/116
  • 5 min

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.

Practice 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");.

Starter code

main.c
#include <stdio.h>
#include <unistd.h>

// Write the getopt loop and switch block
// Print "tamam" after the loop

int main(int argc, char *argv[]) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the getopt call

Question
while ((opt = getopt(argc, argv, "____")) != -1)
Answer
while ((opt = getopt(argc, argv, "vn:")) != -1)

Explanation: The vn: string defines the v flag and n: with an argument.

2 Match the getopt parts

Term Meaning
getopt Option parser
optarg Argument value
vn: Option string
-1 Scan finished

3 What does optarg hold?

  • The option count
  • The program name
  • The value of an option that takes an argument Correct answer
  • An error code

Explanation: optarg holds the argument value for options marked with a colon (e.g. n:).

All lessons in Intermediate