getopts-0.1
About:
getopts is a C library for reading and parsing command line parameters (argc and argv). It supports
- options with a short- and a long name; i.e. an option with the short name “h” and the long name “help” can be used as “-h”, “/h” or “–help”
- options with a parameter; i.e. an option “input” (short “in”) with a parameter “filename” can be used like this: “-in [filename]“, “/in [filename]“, “–input:[filename]“, “–input=[filename]” or “–input [filename]“
- parameters (without an option); i.e. grep accepts several options, and the last command line parameter usually is the filename: “grep -i needle haystack.txt” in this case the filename would be the parameter.
getopts() also provides the function getopts_usage(), which generates the “help-screen” and prints all options and arguments.
Download:
http://www.crupp.de/dl/getopts-0.1.tar.gz
Usage:
getopts() works with an option-table, which is described below.
Here is an example for a function which accepts two options:
-h/--help for the help screen -f/--file for the filename (this option needs an argument)
In this case, the table would look like this:
option_t opts[]={ { ARG_HELP, // symbolic name of this option "h", // short option "help", // long option "this help screen", // help string 0 }, // no flags { ARG_FILE, // symbolic name of this option "f", // short option "file", // long option "input file name", // help string GETOPTS_NEED_ARGUMENT }, // this option needs an argument { 0, 0, 0, 0, 0 } // the terminating entry };
In this example, the constants ARG_HELP and ARG_FILE could be defined as 1 or 2 (you can use any number but 0, and you should avoid the predefined values, which are defined in getopts.h).
Your first step now would be to initialize getopts() with your argc/argv values. The last parameter is your program name – it will appear in your help screen. You can use argv[0] or any other identifier.
getopts_init(argc, argv, "test");
Now the parameters can be checked with getopts(). getopts() will return the symbolic name of the parameter, or one of the predefined constants defined below (i.e. GETOPTS_UNKNOWN for an unknown parameter).
Note that the variable ‘param’ receives the parameter of the –file-option. In case of an unknown parameter, ‘param’ will receive the value of the unknown parameter.
unsigned int opt; char *param; while ((opt=getopts(&opts[0], ¶m))) { if (opt==ARG_HELP) { getopts_usage(&opts[0]); } else if (opt==ARG_FILE) { printf("getopt: file is %sn", param); } else if (opt==GETOPTS_UNKNOWN) { printf("getopt: unknown parameter %sn", param); } // etc... }
Example code:
An example (sample.c) is provided in the tarball.
Changes:
None so far.
Copyright:
(C) Christoph Rupp, chris at crupp.de
The library is released under the zlib license. You can use it for whatever you want, without limitations. It is provided without warranties. The license text is at the top of the header file getopts.h.
Comments:
Please leave comments here: http://www.crupp.de/?p=7