- Notifications
You must be signed in to change notification settings - Fork1
C library for parsing command line option and configuration files.
License
P1sec/libcfg
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This is a fork of initial author Cheng Zhao'slibcfglibrary.
This is a simple library written in C, for parsing command lineoptions and plain configuration files. It can be used to retrievevariables and arrays into runtime memory, or call functions indicatedby command line flags.
This library is compliant with the ISO C99 standard, and relies onlyon the C standard library. It is originaly written by Cheng Zhao(赵成), and is distributed under theMITlicense.
It has been renamed tolibcfgcli
and now maintained by Gregory David.
Since this library is tiny and portable, it is recommended to compilethe only two source files —libcfgcli.h
andlibcfgcli.c
— along with your own program. To this end, one only needs toinclude the headerlibcfgcli.h
in the source file for parsingconfigurations:
#include"libcfgcli.h"
You can also set this library as shared onto your system. Use thestandard autotools suite.
autoreconf -fi./configure --prefix=/usr/localmakesudo make install
Library header should now be installed in/usr/local/include/libcfgcli.h
.
Feel free to usepkg-config
to access compilation flags.
Include the header in top of your code.
#include<libcfgcli.h>
Compile withpkg-config
:
gcc $(pkg-config --cflags --libs cfgcli) -o example example.c
Compile without:pkg-config
gcc -I/usr/local/include -lcfgcli -o example example.c
Acfgcli_t
type structure has to be initialised in the first place, forstoring all the configuration information. This can be done using thefunctioncfgcli_init
, e.g
cfgcli_t*config_ptr=cfgcli_init();
This function returns theNULL
pointer on error.
To retrieve variables and arrays from command line options orconfiguration files, they need to be registered as configurationparameters, which are represented by thecfgcli_param_t
typestructure:
typedefstruct {intopt;/* short command line option */char*lopt;/* long command line option */char*name;/* name of the parameter */cfgcli_dtype_tdtype;/* data type of the parameter */void*var;/* variable for the retrieved value */char*help;/* help message for the parameter */}cfgcli_param_t;
The format of the attributes are:
opt
: a single case-sensitive letter or0
;lopt
: a string composed of characters with graphicalrepresentations (ensured byisgraph),or aNULL
pointer;name
: a string composed of case-sensitive letters, digits, andthe underscore character, and starting with either a letter or anunderscore;dtype
: a pre-defined data type indicator;var
: pointer to the address of the variable/array for holdingthe retrieved value, and no memory allocation is needed;help
: a string defining the help message for the parameter.
In particular, ifopt
is set to0
, orlopt
is set toNULL
, thevalue will not be retrieved from short or long command line options,respectively. For safety consideration, the length oflopt
andname
must be smaller than the pre-definedCFGCLI_MAX_LOPT_LEN
andCFGCLI_MAX_NAME_LEN
values respectively.
The supported data types and their indicators are listed below:
Data type | Indicator | Native C type |
---|---|---|
Boolean variable | CFGCLI_DTYPE_BOOL | bool |
Character variable | CFGCLI_DTYPE_CHAR | char |
Integer variable | CFGCLI_DTYPE_INT | int |
Long integer variable. | CFGCLI_DTYPE_LONG | long |
Single-precision floating-point number | CFGCLI_DTYPE_FLT | float |
Double-precision floating-point number | CFGCLI_DTYPE_DBL | double |
String variable | CFGCLI_DTYPE_STR | char * |
Boolean array | CFGCLI_ARRAY_BOOL | bool * |
Character array | CFGCLI_ARRAY_CHAR | char * |
Integer array | CFGCLI_ARRAY_INT | int * |
Long integer array | CFGCLI_ARRAY_LONG | long * |
Single-precision floating-point array | CFGCLI_ARRAY_FLT | float * |
Double-precision floating-point array | CFGCLI_ARRAY_DBL | double * |
String array | CFGCLI_ARRAY_STR | char ** |
Once the configuration parameters are set, they can be registeredusing the function
intcfgcli_set_params(cfgcli_t*cfg,constcfgcli_param_t*params,constintnpar);
Here,cfg
indicates the structure for storing all configurationinformation, or the entry for the registration.params
denotes theaddress of the configuration parameter structure, andnpar
indicatesthe number of parameters to be registered at once. This functionreturns0
on success, and a non-zero integer on error.
Note that thecfgcli_param_t
type structure for parameterregistration cannot be deconstructed until the command line optionsand configuration files containing this parameter are parsed (seeParsing command line options andParsing configuration file),
Functions that can be called with command line flags must be declaredwith the prototype
voidfunc(void*args);
Similar to configuration parameters, functions can also be registeredin the form of a structure:
typedefstruct {intopt;/* short command line option */char*lopt;/* long command line option */void (*func) (void*);/* pointer to the function */void*args;/* pointer to the arguments */char*help;/* help message for the function */}cfgcli_func_t;
Theopt
andlopt
variables are the short and long command lineoption for calling this function, respectively. And at least one ofthem has to be set, i.e., a case-sensitive letter foropt
, or astring composed of graphical characters forlopt
. Again, the lengthoflopt
must be smaller than the pre-definedCFGCLI_MAX_LOPT_LEN
limit. The pointersfunc
andargs
are the address of the function to be called, and thecorresponding arguments, respectively.help
is a string defining thehelp message for the function.
The functions can then be registered using
intcfgcli_set_funcs(cfgcli_t*cfg,constcfgcli_func_t*funcs,constintnfunc);
Here,cfg
indicates the entry for the registration,funcs
denotesthe address to the structure holding the registration information offunctions, andnfunc
indicates the number of functions to beregistered at once. This function returns0
on success, and anon-zero integer on error.
Note that thecfgcli_func_t
type structure for function registrationcannot be deconstructed until the command line options are parsed (seeParsing command line options).
As an example, a typical demand for calling functions via command lineis to print the usage of a program, when there is the-h
or--help
flag. In this case, the help function and the corresponding structurecan be defined as
voidhelp(void*cfg) {cfgcli_print_help((cfgcli_t*)cfg);exit(0);}
and registered with
cfgcli_t*cfg=init_config();...constcfgcli_func_thelp_func= {'h',"help",help,cfg,"Print this message and exit."};
Command line options are passed to themain
function at programstartup, as theargc
andargv
parameters. These two parameters canbe used by the functioncfgcli_read_opts
for parsing the options,and retrieving parameter values or calling functions. This function isdefined as
intcfgcli_read_opts(cfgcli_t*cfg,constintargc,char*const*argv,constintpriority,int*optidx);
It returns0
on success, and a non-zero integer on error. And thearguments are:
cfg
: the structure for all configuration information;argc
: the number of command line arguments, obtained frommain
;argv
: the command line argument list, obtained frommain
;priority
: the priority of values retrieved from command line,must be positive;optidx
: the index of the argument list at which the parser isterminated.
In particular,priority
decides which value to take if the parameteris defined in multiple sources, say, both in a configuration file andcommand line options. For instance, if a variable has already been setin a configuration file with a lowerpriority
value than the onepassed tocfgcli_read_opts
, then its value will be overwritten bythe one obtained from command line.
The supported formats of command line options are listed below:
Description | Format | Example | Note |
---|---|---|---|
Short option | -OPT VALUE or -OPT=VALUE | -n=10 | OPT must be a letter;VALUE is optional. |
Long option | --LOPT VALUE or --LOPT=VALUE | --help | LOPT is a string with graphical characters,with length smaller than CFGCLI_MAX_LOPT_LEN ;VALUE is optional. |
Option terminator | -- | It terminates option scanning. |
Note that the-
and=
symbols in the formats arecustomisable. They are actually defined asCFGCLI_CMD_FLAG
andCFGCLI_CMD_ASSIGN
inlibcfgcli.h
, respectively.
All command line arguments satisfying the above formats areinterpreted as options, otherwise they are treated as values. Andvalues can only be omitted for boolean type variables — whichimpliestrue
— or function calls. If the value contains spaceor special characters that are reserved by the environment, then itshould be enclosed by pairs of single or double quotationmarks. Besides, values that may be confused with options (such as-x
) are recommended to be passed with the assignment symbol=
.
Furthermore, if the--
option is found, then the option scanningwill be terminated, and the current index of the argument list isreported asoptidx
. Therefore, when calling the program, non-optionparameters should always be passed after all the options. And whenoptidx
is equal toargc
, it means that all command line argumentsare parsed.
Plain text files can be parsed using the function
intcfgcli_read_file(cfgcli_t*cfg,constchar*filename,constintpriority);
The argumentcfg
indicates the structure for storing allconfiguration information,filename
denotes the name of the inputfile, andpriority
defines the priority of values read from thisfile. This function returns0
on success, and a non-zero integer onerror.
By default the format of a valid configuration file has to be
# This is a comment.name_variable = value # inline commentname_array = [ element1, element2 ] # entry for an array
Here,name_variable
andname_array
indicate the registered name ofconfiguration parameters (seeParameterregistration), andvalue
,element1
, andelement2
are the values to be loaded into memory.
In particular, scalar type definitions can be parsed as arrays with asingle element. And by default array type definitions with multipleelements have to be enclosed by a pair of brackets[]
. In addition,multiple-line definitions are only allowed for arrays, and the linebreak symbol\
can only be placed after the array element separator,
. These symbols, including[
,]
,\
,,
, as well as thecomment indicator#
, are customisable inlibcfgcli.h. And if a value or an element of anarray contains special characters, the full value or element has to beenclosed by a pair of single or double quotation marks.
The functionscfgcli_read_opts
andcfgcli_read_file
extract theparameter value from command line options and configuration filesrespectively. The value is then converted to the given data type, andpassed to the address of the variable specified at registration.
To verify whether a variable or an array is set correctly, one can usethe function
boolcfgcli_is_set(constcfgcli_t*cfg,constvoid*var);
It returnstrue
if the variable or array values are set by thefunctionscfgcli_read_opts
orcfgcli_read_file
, andfalse
ifthey are untouched. Here,var
has to be the variable/array addressspecified at registration.
Moreover, the number of array elements read by the parser can bereported by the function
intcfgcli_get_size(constcfgcli_t*cfg,constvoid*var);
It returns0
if the array is not set. So it may not be necessary toverify arrays usingcfgcli_is_set
. Note that the array is allocatedwith precisely the number of elements reported by this function, sothe indices for accessing array elements must be smaller than thisnumber.
Once the variable or array is verified successfully, it can then beused directly in the rest parts of the program.
Once all the variables and arrays are retrieved and verified, thecfgcli_t
type structure for storing all the configurationinformation can be deconstructed by the function
voidcfgcli_destroy(cfgcli_t*cfg);
After calling this function, the values of the variables and arraysare still accessible, but the size of arrays cannot be obtained usingthecfgcli_get_size
function anymore.
In addition, since the memory of arrays and string variables areallocated by this library, it is the user's responsibility to freethem using the standardfree
function. In particular, since stringarrays are represented two-dimensional character arrays, the pointersto both the string array and its first element have to be freed, e.g.
char**str;/* declaration of the string array *//* parameter registration and retriving */free(*str);/* free the first element of the array */free(str);/* free the array itself */
Errors can be caught by checking the return values of some of thefunctions, such ascfgcli_init
,cfgcli_set_params
,cfgcli_read_opts
, etc. And once thecfgcli_init
is executedsuccessfully, error messages can be printed using the function
voidcfgcli_perror(constcfgcli_t*cfg,FILE*stream,constchar*msg);
It outputs the string indicated bymsg
, followed by a colon and aspace, and then followed by the error message produced by thislibrary, as well as a newline character\n
. The results are writtentostream
, which is typicallystderr
.
Unexpected issues that are not critical enough to stop the program aretreated as warnings. They cannot be handled by the return values offunctions, but one can check warning messages using the function
voidcfgcli_pwarn(cfgcli_t*cfg,FILE*stream,constchar*msg);
This function is similar tocfgcli_perror
. Note that there can bemultiple warning messages, and once a warning message is printed, itis automatically removed from the message pool.
An example for the usage of this library is provided in thetests folder.
It registers variables and arrays for all the supported data types, aswell as two functions to be called via command line (--help
and--license
). Command line options and the configuration fileinput.conf
are then parsed. The variables andarrays are printed if they are set correctly.