Skip to content
Snippets Groups Projects

getopt

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Stephan Boekelmann

    This program demonstrates a simple usage of getopt to parse two options: -h and -v. If the user runs the program with the -h option, it prints a help message and exits. If the -v option is used, it sets a verbosity flag to 1 (true), indicating that verbose mode is on, and then it prints a message indicating whether verbose mode is activated.

    Edited
    main.h 851 B
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[]) {
        int opt;
        int verbose = 0;
    
        while ((opt = getopt(argc, argv, "hv")) != -1) {
            switch (opt) {
                case 'h':
                    printf("Usage: %s [-h] [-v]\n", argv[0]);
                    printf("  -h  Display this help and exit\n");
                    printf("  -v  Increase verbosity\n");
                    exit(EXIT_SUCCESS);
                case 'v':
                    verbose = 1;
                    break;
                default: /* '?' */
                    fprintf(stderr, "Usage: %s [-h] [-v]\n", argv[0]);
                    exit(EXIT_FAILURE);
            }
        }
    
        if (verbose) {
            printf("Verbose mode is on.\n");
        } else {
            printf("Verbose mode is off.\n");
        }
    
        // Your program's logic goes here
    
        return EXIT_SUCCESS;
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment