getopt() function in C to parse command line arguments

C++Server Side ProgrammingProgramming

The getopt() is one of the built-in C function that are used for taking the command line options. The syntax of this function is like below −

getopt(int argc, char *const argv[], const char *optstring)

The opstring is a list of characters. Each of them representing a single character option.

This function returns many values. These are like below −

  • If the option takes a value, then that value will be pointed by optarg.
  • It will return -1, when no more options to proces
  • Returns ‘?’ to show that this is an unrecognized option, it stores it to optopt.
  • Sometimes some options need some value, If the option is present but the values are not there, then also it will return ‘?’. We can use ‘:’ as the first character of the optstring, so in that time, it will return ‘:’ instead of ‘?’ if no value is given.

Example

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

main(int argc, char *argv[]) {
   int option;
   // put ':' at the starting of the string so compiler can distinguish between '?' and ':'
   while((option = getopt(argc, argv, ":if:lrx")) != -1){ //get option from the getopt() method
      switch(option){
         //For option i, r, l, print that these are options
         case 'i':
         case 'l':
         case 'r':
            printf("Given Option: %c\n", option);
            break;
         case 'f': //here f is used for some file name
            printf("Given File: %s\n", optarg);
            break;
         case ':':
            printf("option needs a value\n");
            break;
         case '?': //used for some unknown options
            printf("unknown option: %c\n", optopt);
            break;
      }
   }
   for(; optind < argc; optind++){ //when some extra arguments are passed
      printf("Given extra arguments: %s\n", argv[optind]);
   }
}

Output

Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Given extra arguments: hello
raja
Published on 06-May-2019 12:51:50
Advertisements