Parse command line options using getopt() ..

Home Forums C-programming.. Parse command line options using getopt() ..

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2099 Reply
    Humble
    Keymaster

    I have seen lots of programs where the command line options are parsed differently and have seen that lots of logic/effort behind those programs which is not much needed.. 🙂 .. That said, the function getopt() ( also getopt_long()) can simplify the command line option parsing in a massive amount . So, use it for your programs.

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    int print_usage( )
    {
    
    	fprintf(stderr, " \n Usage :./<program name> -i <input file> -o <output file> [vh?] \n" );
    	exit(1);
    
    }
    int main (int argc, char *argv[])
    {
    
    	int option;
    	int i,verbose=0;
    	char *inputfile = NULL;
     	char *outputfile = NULL;
    
    	if ( argc < 5)
    	{
    		print_usage();
    	}
    	else
    	{
    		while ( (option = getopt(argc, argv, "i:o:hv")) != -1)
    		{
    
    			switch (option){
    
    			case 'i':
    				inputfile = optarg;
    				break;
    			case 'o':
    				outputfile = optarg;
    				break;
    			case 'v':
    				verbose = 1;
    				printf ("Verbose enabled:\n");
    				break;
    			case 'h':
    			case '?':
    				print_usage();
    				return 1;
    				
    			default:
    				print_usage();
    			}
    		}
    	}
    	if (optind < argc)
    		printf( "Non-option arguments \n");
    	for (i = optind; i <argc; i++)
    	{
    		printf ("%s\n", argv[i]);
    	}
    
    	return 0;
    }
    [root@node]$
    
    
    
    
    Above is a very simplified version of the getopt() example program which accepts command line switches "-i" and "-o" with argument values.. 
    
    [Explain above program && getopt parameters]
    
    If we execute above program using different command line switches we could see these outputs:
    
    [ root@node]$ ./parse_arg -i asd.txt -o hu.txt -v
    Verbose enabled:
    [ root@node]$ ./parse_arg -i asd.txt -o hu.txt asd
    Non-option arguments 
    asd
    [ root@node]$ ./parse_arg -i asd.txt -o hu.txt 
    [root@node]$ ./parse_arg -i asd.txt -o hu.txt -h
     
     Usage :./<program name> -i <input file> -o <output file> [vh?] 
    [ root@node]$ ./parse_arg -i asd.txt -o hu.txt -v
    Verbose enabled:
    [root@node]$ ./parse_arg -i asd.txt -k hu.txt -v
    ./parse_arg: invalid option -- 'k'
     
     Usage :./<program name> -i <input file> -o <output file> [vh?] 
    
    
Viewing 1 post (of 1 total)
Reply To: Parse command line options using getopt() ..
Your information: