Pejman Moghadam / C-programming

C - Access command-line arguments using getopt_long

Public domain


#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char* argv[])
{
        int next_option,i;

        /* "ho:v" short options means there is -h, -o (with an atgument) 
           and -v options */
        const char* const short_options = "ho:v";

        /* An array describing valid long options. */
        const struct option long_options[] = {
                { "help",    0, NULL, 'h' },
                { "output",  1, NULL, 'o' },
                { "verbose", 0, NULL, 'v' },
                { NULL,       0, NULL, 0   }   /* Required at end of array.  */
        };

        /* Whether to display verbose messages.   */ 
        int verbose = 0; 


        do {
                next_option = getopt_long (argc, argv, short_options,
                                                 long_options, NULL); 
                switch (next_option)
                {
                case 'h':
                        fprintf (stdout, "-h or --help found: " 
                                         "Here goes your help ...\n");
                        break; 

                case 'o':
                        fprintf (stdout, "-o or --ouput found: " 
                                         "Argument is : %s\n",optarg);
                        break; 

                case 'v':
                        fprintf (stdout, "-v or  --verbose found: "
                                         "Verbose flag will be set\n",optarg);
                        break; 

                case '?':
                        fprintf (stdout, "Invalid option found !!!\n");
                        break; 
                case -1:
                        fprintf (stdout, "End of option list reached.\n");
                        break; 

                default:
                        fprintf (stdout, "getopt_long returned unexpected value.\n");
                        abort ();
                }
        }
        while (next_option != -1);

        fprintf (stdout, "non-option argument goes here if exist: \n");
        for (i = optind; i < argc; ++i)
                    printf ("Argument: %s\n", argv[i]); 

        return 0; 
}

Output

$ ./a.out -o abc.txt -h -v "test ing" additional "argu ments"
-o or --ouput found: Argument is : abc.txt
-h or --help found: Here goes your help ...
-v or  --verbose found: Verbose flag will be set
End of option list reached.
non-option argument goes here if exist: 
Argument: test ing
Argument: additional
Argument: argu ments

BY: Pejman Moghadam
TAG: c, getopt
DATE: 2011-05-28 23:38:24


Pejman Moghadam / C-programming [ TXT ]