getopt() function in C to parse command line arguments

The getopt() function is a builtin function in C and is used to parse command line arguments.

Syntax:

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

optstring is simply  a list of characters, 
each representing a single character option.

Return Value: The getopt() function returns different values:

Generally, the getopt() function is called from inside of a loop’s conditional statement. The loop terminates when the getopt() function returns -1. A switch statement is then executed with the value returned by getopt() function.

A second loop is used to process the remaining extra arguments that cannot be processed in the first loop.



Below program illustrate the getopt() function in C:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to illustrate the getopt()
// function in C
  
#include <stdio.h> 
#include <unistd.h> 
  
int main(int argc, char *argv[]) 
{
    int opt;
      
    // put ':' in the starting of the
    // string so that program can 
    //distinguish between '?' and ':' 
    while((opt = getopt(argc, argv, “:if:lrx”)) != -1) 
    
        switch(opt) 
        
            case ‘i’: 
            case ‘l’: 
            case ‘r’: 
                printf(“option: %c\n”, opt); 
                break
            case ‘f’: 
                printf(“filename: %s\n”, optarg); 
                break
            case ‘:’: 
                printf(“option needs a value\n”); 
                break
            case ‘?’: 
                printf(“unknown option: %c\n”, optopt);
                break
        
    
      
    // optind is for the extra arguments
    // which are not parsed
    for(; optind < argc; optind++){     
        printf(“extra arguments: %s\n”, argv[optind]); 
    }
      
    return 0;
}
chevron_right

Output:

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




Article Tags :
C
Practice Tags :