Home > Back-end >  Using getopt to parse command line options and their arguments
Using getopt to parse command line options and their arguments

Time:08-31

I am trying to use getopt to parse command line options passed by the user of the program. I am specifically struggling with how to save the "option arguments" that are passed with flag, for example like below.

./main -r 213

I am trying to set it up in a way where argument order doesn't matter, and several of my options could pass strings as their argument that I would like to save to a variable. I.e., like below.

./main -o bmp

I have been looking at several resources, but am having trouble even getting the basic ones to print out. For example the code below:

int r, g, b, c;
char t[3];
while ((c = getopt (argc, argv, "abc:")) != -1)
    switch (c)
      {
      case 'r':
        printf("Option r has option %s\n", optarg);
        break;
      case 'g':
        printf("Option g has option %s\n", optarg);
        break;
      case 'b':
        printf("Option b has option %s\n", optarg);
        break;
        break;
      case 't':
        printf("Option t has option %s\n", optarg);
        break;
      }

When given this command line argument:

./main -r 123 -g 89 -b -76

Produces this:

./main: invalid option -- 'r'

./main: invalid option -- 'g'

Option b has option (null)

./main: invalid option -- '7'

./main: invalid option -- '6'

Like I mentioned what I actually want to do is store these option arguments off, but I was trying this to understand how they're structured.

CodePudding user response:

Your optstring abc: is incorrect. It should be b:g:r:t: if they all require a value:

#define _POSIX_C_SOURCE 2
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char c;
    while ((c = getopt (argc, argv, "b:g:r:t:")) != -1) {
        switch (c) {
            case 'b':
                printf("Option b has option %s\n", optarg);
                break;
            case 'g':
                printf("Option g has option %s\n", optarg);
                break;
            case 'r':
                printf("Option r has option %s\n", optarg);
                break;
            case 't':
                printf("Option t has option %s\n", optarg);
                break;
        }
    }
    return 0;
}

and here is the output for your example:

$ ./main -r 123 -g 89 -b -76
Option r has option 123
Option g has option 89
Option b has option -76
  • Related