In short:
optopt , optind and optarg are external characters. They are global and declared in unistd.h .
optopt ( opt = option ) is usually not required. It should be the same as the value returned by the getopt call.
optarg ( arg = argument ) is easy. This is for the argument for the flag. for example, if -f is a parameter that requires a file name argument ( optstring contains f: , you can do something like
case 'f': filename = optarg; break;
optind ( ind stands for index ) tells you where the selection process ended after the end of your while (flag = getopt...) block while (flag = getopt...) .
eg. before adding parameter handling, your script might look like this:
// print command line arguments, start at 1 to skip the program name for (int i = 1; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); }
after adding the getopt block to process the parameters, you can do
// print command line arguments remaining after option processing for (int i = optind; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); }
or
// skip command line options argc -= optind; argv += optind; // print command line arguments for (int i = 0; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); }
Unless you have the necessary command line arguments, you don't need to worry about optind .
source share