Parsing¶
The Argtable3 library provides a comprehensive API for parsing command-line options in a structured and efficient manner. This API simplifies the process of defining, validating, and processing command-line arguments, making it easier to build robust and user-friendly command-line applications.
The parsing API supports a wide range of argument types, including boolean flags, integers, doubles, strings, regular expressions, file paths, and dates. It also provides utility functions for managing argument tables, checking for null arguments, and freeing allocated resources.
Key Features¶
Core Parsing Functions: Functions like
arg_parse
handle the parsing of command-line arguments, whilearg_nullcheck
ensures the validity of argument tables.Argument Table Management: Use
arg_end
to define the end of an argument table andarg_freetable
to release resources associated with it.Support for Multiple Argument Types:
Boolean Options: Functions such as
arg_lit0
,arg_lit1
, andarg_litn
handle boolean flags.Integer Options: Functions like
arg_int0
,arg_int1
, andarg_intn
parse integer arguments.Double Options: Use
arg_dbl0
,arg_dbl1
, andarg_dbln
for floating-point arguments.String Options: Functions such as
arg_str0
,arg_str1
, andarg_strn
manage string arguments.Regex Options: Use
arg_rex0
,arg_rex1
, andarg_rexn
to parse arguments matching regular expressions.File Options: Functions like
arg_file0
,arg_file1
, andarg_filen
handle file paths.Date Options: Use
arg_date0
,arg_date1
, andarg_daten
to parse date arguments.
Miscellaneous: The
arg_rem
function allows for defining custom argument types.
This API is designed to provide flexibility and ease of use, enabling developers to focus on the functionality of their applications rather than the intricacies of argument parsing. Below is a detailed reference for each function in the command-line parsing API.
Data Types¶
-
typedef struct arg_hdr arg_hdr_t¶
Defines common properties shared by all
arg_<type>
structs.In the Argtable3 library, every
arg_<type>
struct must begin with anarg_hdr
struct as its first member. This allows Argtable3 functions to access shared metadata about the command-line option, such as its option tags, data type string, glossary text, and other attributes.The
arg_hdr
struct also contains pointers to type-specific functions provided by eacharg_<type>
implementation. These functions handle tasks such as parsing the option, performing post-parse validation, and reporting errors. Although these function pointers are initialized by the constructor of the respectivearg_<type>
struct, they can be modified by the user after construction if necessary. However, they are intended to remain unchanged once initialized.
-
typedef struct arg_rem arg_rem_t¶
Structure for storing remarks or custom lines in the syntax or glossary output.
The
arg_rem
struct is used to add extra lines of text to the syntax or glossary output generated by Argtable3. Unlike other argument types,arg_rem
does not correspond to a command-line argument and does not affect argument parsing. Instead, it is a dummy entry that allows you to insert remarks, explanations, or custom formatting into the help or usage messages.This is especially useful for providing additional context, grouping related options, or clarifying the usage of certain arguments in the generated documentation.
Example usage:
// Add extra lines to the glossary for the --update option arg_lit_t *update = arg_litn("u", "update", 0, 1, "copy only when SOURCE files are"); arg_rem_t *update1 = arg_rem(NULL, " newer than destination files"); arg_rem_t *update2 = arg_rem(NULL, " or when destination files"); arg_rem_t *update3 = arg_rem(NULL, " are missing"); void *argtable[] = { update, update1, update2, update3, ... }; // Add a data type entry for a positional argument in the syntax arg_rem_t *dest = arg_rem("DEST|DIRECTORY", NULL); void *argtable[] = { ..., dest, ... };
See also
arg_rem()
-
typedef struct arg_lit arg_lit_t¶
Structure for storing literal (boolean flag) argument information.
The
arg_lit
struct is used to parse and store literal arguments (boolean flags) from the command line. It is suitable for options that do not take a value, such as-h
for help or--verbose
for enabling verbose output. Each occurrence of the flag increases thecount
field, allowing you to detect how many times the flag was specified.Example usage:
// Accepts a help flag and a verbose flag (which can be specified multiple times) arg_lit_t *help = arg_lit0("h", "help", "Display help"); arg_lit_t *verbose = arg_litn("v", "verbose", 0, 3, "Increase verbosity"); arg_end_t *end = arg_end(20); void *argtable[] = { help, verbose, end }; int nerrors = arg_parse(argc, argv, argtable); if (help->count > 0) { printf("Help requested\n"); } if (verbose->count > 0) { printf("Verbosity level: %d\n", verbose->count); }
See also
arg_lit0, arg_lit1, arg_litn
-
typedef struct arg_int arg_int_t¶
Structure for storing int-typed argument information.
The
arg_int
struct is used to parse and store integer arguments from the command line. It is suitable for options that accept numeric values without fractional parts, such as counts, indices, or other whole-number parameters.The
count
field stores the number of successfully matched integer arguments, and theival
array holds the parsed integer values as provided by the user.Example usage:
// Accepts one or more integer arguments arg_int_t *numbers = arg_intn("n", "number", "<int>", 1, 5, "Input numbers"); arg_end_t *end = arg_end(20); void *argtable[] = {numbers, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && numbers->count > 0) { for (int i = 0; i < numbers->count; ++i) { printf("Input number: %d\n", numbers->ival[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_int0, arg_int1, arg_intn
-
typedef struct arg_dbl arg_dbl_t¶
Structure for storing double-typed argument information.
The
arg_dbl
struct is used to parse and store double-precision floating-point arguments from the command line. It is suitable for options that accept numeric values with fractional parts, such as thresholds, ratios, or measurements.The
count
field stores the number of successfully matched double arguments, and thedval
array holds the parsed double values as provided by the user.Example usage:
// Accepts one or more double arguments arg_dbl_t *values = arg_dbln("v", "value", "<double>", 1, 5, "Input values"); arg_end_t *end = arg_end(20); void *argtable[] = {values, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && values->count > 0) { for (int i = 0; i < values->count; ++i) { printf("Input value: %f\n", values->dval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_dbl0, arg_dbl1, arg_dbln
-
typedef struct arg_str arg_str_t¶
Structure for storing string-typed argument information.
The
arg_str
struct is used to parse and store string arguments from the command line. It is suitable for options that accept arbitrary text input, such as file names, user names, or other string values.The
count
field stores the number of successfully matched string arguments, and thesval
array holds the parsed string values as provided by the user.Example usage:
// Accepts one or more string arguments arg_str_t *inputs = arg_strn(NULL, NULL, "<input>", 1, 10, "Input strings"); arg_end_t *end = arg_end(20); void *argtable[] = {inputs, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && inputs->count > 0) { for (int i = 0; i < inputs->count; ++i) { printf("Input string: %s\n", inputs->sval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_str0, arg_str1, arg_strn
-
typedef struct arg_rex arg_rex_t¶
Structure for storing regular expression-typed argument information.
The
arg_rex
struct is used to parse and store command-line arguments that must match a specified regular expression pattern. This allows applications to validate input against complex patterns, such as email addresses, identifiers, or custom formats.The
pattern
is specified when constructing the argument and is used to check each input value. Thecount
field stores the number of successfully matched arguments, and thesval
array holds the matched strings.Example usage:
// Accepts one or more arguments matching a simple email pattern arg_rex_t *emails = arg_rexn(NULL, "email", "^[^@]+@[^@]+\\.[^@]+$", "<email>", 1, 10, 0, "Email addresses"); arg_end_t *end = arg_end(20); void *argtable[] = {emails, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && emails->count > 0) { for (int i = 0; i < emails->count; ++i) { printf("Matched email: %s\n", emails->sval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_rex0, arg_rex1, arg_rexn
-
typedef struct arg_file arg_file_t¶
Structure for storing file-typed argument information.
The
arg_file
struct is used to parse and store file path arguments from the command line. It provides convenient access to the full filename, the basename (file name without path), and the file extension for each matched argument. This allows applications to easily process and validate file-related options.The
count
field stores the number of successfully matched file arguments. Thefilename
array holds the full file paths as provided by the user, while thebasename
andextension
arrays provide the corresponding file names and extensions, respectively.Example usage:
// Accepts one or more file arguments arg_file_t *files = arg_filen(NULL, NULL, "<file>", 1, 100, "Input files"); arg_end_t *end = arg_end(20); void *argtable[] = {files, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && files->count > 0) { for (int i = 0; i < files->count; ++i) { printf("File: %s, Basename: %s, Extension: %s\n", files->filename[i], files->basename[i], files->extension[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_file0, arg_file1, arg_filen
-
typedef struct arg_date arg_date_t¶
Structure for storing date-typed argument information.
The
arg_date
struct is used to parse and store date or time arguments from the command line. It supports flexible date/time formats, which are specified using astrptime
-style format string. Each successfully parsed date argument is converted into astruct tm
value and stored in thetmval
array.The
format
field defines the expected input format for date arguments, allowing you to accept a wide range of date/time styles. Thecount
field stores the number of successfully matched arguments, and thetmval
array holds the parsed results.Example usage:
// Accepts one required date argument in YYYY-MM-DD format arg_date_t *date = arg_date1(NULL, "date", "%Y-%m-%d", "<date>", "Date in YYYY-MM-DD format"); arg_end_t *end = arg_end(20); void *argtable[] = {date, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && date->count > 0) { printf("Parsed date: %04d-%02d-%02d\n", date->tmval[0].tm_year + 1900, date->tmval[0].tm_mon + 1, date->tmval[0].tm_mday); } else { arg_print_errors(stdout, end, argv[0]); }
See also
arg_date0, arg_date1, arg_daten
-
typedef struct arg_end arg_end_t¶
Structure for collecting parser errors and terminating an argument table.
The
arg_end
struct is used in Argtable3 to mark the end of an argument table and to collect information about any errors encountered during command-line parsing. It stores pointers to offending arguments in the input array, allowing the application to report detailed error messages to the user.Typically, an
arg_end_t
instance is created using thearg_end
function and placed as the last element in the argument table array. After parsing, the structure contains information about missing required arguments, invalid values, or other parsing errors.Example usage:
arg_lit_t *help = arg_lit0("h", "help", "Display help"); arg_int_t *count = arg_int0("c", "count", "<n>", "Number of times"); arg_end_t *end = arg_end(20); void *argtable[] = {help, count, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors > 0) { arg_print_errors(stdout, end, argv[0]); // handle errors... }
API¶
-
int arg_parse(int argc, char **argv, void **argtable)¶
Parses the command-line arguments according to the specified argument table.
The
arg_parse
function processes the command-line arguments provided inargv
and populates the fields of each argument structure in theargtable
array. It checks for the presence, validity, and value of each option or positional argument as defined by the argument table. Any errors encountered during parsing, such as missing required arguments or invalid values, are recorded in thearg_end_t
structure (typically the last entry in the table).After calling
arg_parse
, you can inspect the fields of each argument struct (such ascount
,ival
,dval
,sval
, etc.) to retrieve the parsed values. If errors are detected (i.e., the return value is greater than zero), you can usearg_print_errors
to display detailed error messages to the user.Example usage:
arg_lit_t *help = arg_lit0("h", "help", "Display help"); arg_int_t *count = arg_int0("c", "count", "<n>", "Number of times"); arg_end_t *end = arg_end(20); void *argtable[] = {help, count, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors > 0) { arg_print_errors(stdout, end, argv[0]); // handle errors... }
- Parameters:
argc – The number of command-line arguments passed to the program. The value is always greater than or equal to 1.
argv – An array of null-terminated strings representing the command-line arguments. By convention,
argv[0]
is the program name, andargv[1]
toargv[argc-1]
are the arguments.argv[argc]
is always NULL.argtable – An array of pointers to argument table structs, each created by an
arg_<type>
constructor. The last entry should be anarg_end
struct.
- Returns:
The number of errors found during parsing. Returns 0 if parsing was successful and no errors were detected.
-
int arg_nullcheck(void **argtable)¶
Checks the argument table for null entries.
The
arg_nullcheck
function scans the provided argument table array and returns 1 if any entry is NULL, or 0 if all entries are valid. This is useful for detecting memory allocation failures after constructing all argument table entries witharg_<type>
constructor functions, such asarg_litn
.Instead of checking the return value of each constructor individually, you can call
arg_nullcheck
once after building the argument table to ensure that all arguments were allocated successfully. This helps make your code cleaner and more robust.Example usage:
arg_lit_t *list = arg_lit0("lL",NULL, "list files"); arg_lit_t *verbose = arg_lit0("v","verbose,debug", "verbose messages"); arg_lit_t *help = arg_lit0(NULL,"help", "print this help and exit"); arg_lit_t *version = arg_lit0(NULL,"version", "print version and exit"); arg_end_t *end = arg_end(20); void *argtable[] = {list, verbose, help, version, end}; const char *progname = "myprog"; int exitcode = 0; if (arg_nullcheck(argtable) != 0) { printf("%s: insufficient memory\n", progname); exitcode = 1; goto exit; }
Checks the argument table for null entries.
- Parameters:
argtable – Array of pointers to argument table structs.
- Returns:
Returns 1 if any entry is NULL, 0 if all entries are valid.
-
arg_end_t *arg_end(int maxcount)¶
Creates an end-of-table marker and error collector for the argument table.
The
arg_end
function is used to create anarg_end_t
struct, which should be placed as the last element in the argument table array. This structure serves two purposes: it marks the end of the argument table for the parser, and it collects information about any errors encountered during command-line parsing.The
maxcount
parameter specifies the maximum number of errors that can be recorded. After parsing, thearg_end_t
struct contains details about missing required arguments, invalid values, or other parsing errors, which can be reported to the user using functions likearg_print_errors
.Example usage:
arg_lit_t *help = arg_lit0("h", "help", "Display help"); arg_int_t *count = arg_int0("c", "count", "<n>", "Number of times"); arg_end_t *end = arg_end(20); void *argtable[] = {help, count, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors > 0) { arg_print_errors(stdout, end, argv[0]); // handle errors... }
See also
arg_end_t, arg_parse, arg_print_errors
- Parameters:
maxcount – The maximum number of errors to record during parsing. Choose a value large enough to capture all possible errors.
- Returns:
If successful, returns a pointer to the allocated
arg_end_t
. ReturnsNULL
if there is insufficient memory.
-
void arg_freetable(void **argtable, size_t n)¶
Deallocates or frees all non-null entries in the argument table.
The
arg_freetable
function iterates over the specified argument table array and frees any non-null entries, releasing the memory allocated for each argument structure. This is useful for cleaning up all argument objects created byarg_<type>
constructor functions after you are done parsing and processing command-line arguments.You should call this function once for each argument table array before your program exits to prevent memory leaks.
Example usage:
arg_lit_t *help = arg_lit0("h", "help", "Display help"); arg_int_t *count = arg_int0("c", "count", "<n>", "Number of times"); arg_end_t *end = arg_end(20); void *argtable[] = { help, count, end }; // ... use argtable ... arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
See also
arg_free
- Parameters:
argtable – An array of pointers to argument table structs.
n – The number of structs in the argument table.
Flag Option API¶
-
arg_lit_t *arg_litn(const char *shortopts, const char *longopts, int mincount, int maxcount, const char *glossary)¶
Creates a literal (boolean flag) argument for the command-line parser.
The
arg_litn
function defines an option that does not take a value, such as a boolean flag (e.g.,-h
for help or--verbose
for verbosity). You can specify the minimum and maximum number of times the flag can appear, making it suitable for optional, required, or repeatable flags. Each occurrence of the flag increases thecount
field in the resultingarg_lit_t
struct.A classic example is the
tar
utility, which uses--verbose
or-v
to show the files being worked on astar
is creating an archive:$ tar -cvf afiles.tar apple angst aspic apple angst aspic
Each occurrence of
--verbose
or-v
on the command line increases the verbosity level by one. Therefore, if you need more details on the output, specify it twice:$ tar -cvvf afiles.tar apple angst aspic -rw-r--r-- gray/staff 62373 2006-06-09 12:06 apple -rw-r--r-- gray/staff 11481 2006-06-09 12:06 angst -rw-r--r-- gray/staff 23152 2006-06-09 12:06 aspic
The
arg_litn
function allows you to specify both the minimum and maximum number of times a flag can appear. For convenience and backward compatibility,arg_lit0
is provided as a helper for optional flags (wheremincount = 0
andmaxcount = 1
), andarg_lit1
is a helper for required flags (wheremincount = 1
andmaxcount = 1
). Whilearg_lit0
andarg_lit1
are available, it is recommended to usearg_litn
in new code as it is more explicit and flexible.Example usage:
arg_lit_t *list = arg_litn("lL",NULL, 0, 1, "list files"); arg_lit_t *verbose = arg_litn("v","verbose,debug", 0, 3, "verbosity level"); arg_lit_t *help = arg_litn("h","help", 0, 1, "print this help"); arg_lit_t *version = arg_litn(NULL,"version", 0, 1, "print version info");
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"v"
for-v
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"verbose"
for--verbose
). PassNULL
if no long option is desired.mincount – The minimum number of times the flag must appear (set to 0 for optional).
maxcount – The maximum number of times the flag can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_lit_t
. ReturnsNULL
if there is insufficient memory.
Integer Option API¶
-
arg_int_t *arg_int0(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_int_t *arg_int1(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_int_t *arg_intn(const char *shortopts, const char *longopts, const char *datatype, int mincount, int maxcount, const char *glossary)¶
Creates an integer argument for the command-line parser.
The
arg_intn
function defines an option that accepts integer values from the command line. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable integer options. Each occurrence of the option is parsed and stored in theival
array of the resultingarg_int_t
struct, allowing you to retrieve all provided integer values after parsing.For convenience and backward compatibility,
arg_int0
is provided as a helper for optional integer arguments (wheremincount = 0
andmaxcount = 1
), andarg_int1
is a helper for required integer arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_int0
andarg_int1
are available, it is recommended to usearg_intn
in new code as it is more explicit and flexible.Example usage:
// Accepts one or more integer arguments arg_int_t *numbers = arg_intn("n", "number", "<int>", 1, 5, "Input numbers"); arg_end_t *end = arg_end(20); void *argtable[] = { numbers, end }; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && numbers->count > 0) { for (int i = 0; i < numbers->count; ++i) { printf("Input number: %d\n", numbers->ival[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"n"
for-n
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"number"
for--number
). PassNULL
if no long option is desired.datatype – A string describing the expected data type (e.g.,
"<int>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_int_t
. ReturnsNULL
if there is insufficient memory.
Double Option API¶
-
arg_dbl_t *arg_dbl0(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_dbl_t *arg_dbl1(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_dbl_t *arg_dbln(const char *shortopts, const char *longopts, const char *datatype, int mincount, int maxcount, const char *glossary)¶
Creates a double-precision floating-point argument for the command-line parser.
The
arg_dbln
function defines an option that accepts double-precision floating-point values from the command line. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable floating-point options. Each occurrence of the option is parsed and stored in thedval
array of the resultingarg_dbl_t
struct, allowing you to retrieve all provided double values after parsing.For convenience and backward compatibility,
arg_dbl0
is provided as a helper for optional double arguments (wheremincount = 0
andmaxcount = 1
), andarg_dbl1
is a helper for required double arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_dbl0
andarg_dbl1
are available, it is recommended to usearg_dbln
in new code as it is more explicit and flexible.Example usage:
// Accepts one or more double arguments arg_dbl_t *values = arg_dbln("v", "value", "<double>", 1, 5, "Input values"); arg_end_t *end = arg_end(20); void *argtable[] = {values, end}; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && values->count > 0) { for (int i = 0; i < values->count; ++i) { printf("Input value: %f\n", values->dval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"v"
for-v
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"value"
for--value
). PassNULL
if no long option is desired.datatype – A string describing the expected data type (e.g.,
"<double>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_dbl_t
. ReturnsNULL
if there is insufficient memory.
String Option API¶
-
arg_str_t *arg_str0(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_str_t *arg_str1(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_str_t *arg_strn(const char *shortopts, const char *longopts, const char *datatype, int mincount, int maxcount, const char *glossary)¶
Creates a string argument for the command-line parser.
The
arg_strn
function defines an option that accepts string values from the command line. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable string options. Each occurrence of the option is parsed and stored in thesval
array of the resultingarg_str_t
struct, allowing you to retrieve all provided string values after parsing.For convenience and backward compatibility,
arg_str0
is provided as a helper for optional string arguments (wheremincount = 0
andmaxcount = 1
), andarg_str1
is a helper for required string arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_str0
andarg_str1
are available, it is recommended to usearg_strn
in new code as it is more explicit and flexible.Example usage:
// Accepts one or more string arguments arg_str_t *inputs = arg_strn(NULL, NULL, "<input>", 1, 10, "Input strings"); arg_end_t *end = arg_end(20); void *argtable[] = { inputs, end }; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && inputs->count > 0) { for (int i = 0; i < inputs->count; ++i) { printf("Input string: %s\n", inputs->sval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"i"
for-i
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"input"
for--input
). PassNULL
if no long option is desired.datatype – A string describing the expected data type (e.g.,
"<input>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_str_t
. ReturnsNULL
if there is insufficient memory.
Regular Expression Option API¶
-
arg_rex_t *arg_rex0(const char *shortopts, const char *longopts, const char *pattern, const char *datatype, int flags, const char *glossary)¶
-
arg_rex_t *arg_rex1(const char *shortopts, const char *longopts, const char *pattern, const char *datatype, int flags, const char *glossary)¶
-
arg_rex_t *arg_rexn(const char *shortopts, const char *longopts, const char *pattern, const char *datatype, int mincount, int maxcount, int flags, const char *glossary)¶
Creates a regular expression argument for the command-line parser.
The
arg_rexn
function defines an option that accepts values matching a specified regular expression pattern. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable regex-matched options. Each occurrence of the option is parsed and stored in thesval
array of the resultingarg_rex_t
struct, allowing you to retrieve all provided values that match the regular expression after parsing.For convenience and backward compatibility,
arg_rex0
is provided as a helper for optional regex arguments (wheremincount = 0
andmaxcount = 1
), andarg_rex1
is a helper for required regex arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_rex0
andarg_rex1
are available, it is recommended to usearg_rexn
in new code as it is more explicit and flexible.Example usage:
// Accepts one or more arguments matching a simple email pattern arg_rex_t *emails = arg_rexn(NULL, "email", "^[^@]+@[^@]+\\.[^@]+$", "<email>", 1, 10, 0, "Email addresses"); arg_end_t *end = arg_end(20); void *argtable[] = { emails, end }; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && emails->count > 0) { for (int i = 0; i < emails->count; ++i) { printf("Matched email: %s\n", emails->sval[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"e"
for-e
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"email"
for--email
). PassNULL
if no long option is desired.pattern – The regular expression pattern to match input values.
datatype – A string describing the expected data type (e.g.,
"<email>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
flags – Flags to modify regex matching behavior (e.g.,
ARG_REX_ICASE
for case-insensitive).glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_rex_t
. ReturnsNULL
if there is insufficient memory.
File Option API¶
-
arg_file_t *arg_file0(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_file_t *arg_file1(const char *shortopts, const char *longopts, const char *datatype, const char *glossary)¶
-
arg_file_t *arg_filen(const char *shortopts, const char *longopts, const char *datatype, int mincount, int maxcount, const char *glossary)¶
Creates a file path argument for the command-line parser.
The
arg_filen
function defines an option that accepts file path values from the command line. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable file arguments. Each occurrence of the option is parsed and stored in thefilename
array of the resultingarg_file_t
struct. The struct also provides convenient access to the basename and extension for each file.For convenience and backward compatibility,
arg_file0
is provided as a helper for optional file arguments (wheremincount = 0
andmaxcount = 1
), andarg_file1
is a helper for required file arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_file0
andarg_file1
are available, it is recommended to usearg_filen
in new code as it is more explicit and flexible.Example usage:
// Accepts one or more file arguments arg_file_t *files = arg_filen(NULL, NULL, "<file>", 1, 100, "Input files"); arg_end_t *end = arg_end(20); void *argtable[] = { files, end }; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && files->count > 0) { for (int i = 0; i < files->count; ++i) { printf("File: %s, Basename: %s, Extension: %s\n", files->filename[i], files->basename[i], files->extension[i]); } } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"f"
for-f
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"file"
for--file
). PassNULL
if no long option is desired.datatype – A string describing the expected data type (e.g.,
"<file>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_file_t
. ReturnsNULL
if there is insufficient memory.
Date Option API¶
-
arg_date_t *arg_date0(const char *shortopts, const char *longopts, const char *format, const char *datatype, const char *glossary)¶
-
arg_date_t *arg_date1(const char *shortopts, const char *longopts, const char *format, const char *datatype, const char *glossary)¶
-
arg_date_t *arg_daten(const char *shortopts, const char *longopts, const char *format, const char *datatype, int mincount, int maxcount, const char *glossary)¶
Creates a date/time argument for the command-line parser.
The
arg_daten
function defines an option that accepts date or time values from the command line. You can specify the minimum and maximum number of times the argument can appear, making it suitable for optional, required, or repeatable date/time arguments. Each occurrence of the option is parsed using the specifiedformat
(astrptime
-style format string) and stored as astruct tm
value in thetmval
array of the resultingarg_date_t
struct, allowing you to retrieve all provided date/time values after parsing.For convenience and backward compatibility,
arg_date0
is provided as a helper for optional date arguments (wheremincount = 0
andmaxcount = 1
), andarg_date1
is a helper for required date arguments (wheremincount = 1
andmaxcount = 1
). Whilearg_date0
andarg_date1
are available, it is recommended to usearg_daten
in new code as it is more explicit and flexible.Example usage:
// Accepts one required date argument in YYYY-MM-DD format arg_date_t *date = arg_date1(NULL, "date", "%Y-%m-%d", "<date>", "Date in YYYY-MM-DD format"); arg_end_t *end = arg_end(20); void *argtable[] = { date, end }; int nerrors = arg_parse(argc, argv, argtable); if (nerrors == 0 && date->count > 0) { printf("Parsed date: %04d-%02d-%02d\n", date->tmval[0].tm_year + 1900, date->tmval[0].tm_mon + 1, date->tmval[0].tm_mday); } else { arg_print_errors(stdout, end, argv[0]); }
- Parameters:
shortopts – A string of single characters, each representing a short option name (e.g.,
"d"
for-d
). PassNULL
if no short option is desired.longopts – A string of comma-separated long option names (e.g.,
"date"
for--date
). PassNULL
if no long option is desired.format – A
strptime
-style format string describing the expected date/time input (e.g.,"%Y-%m-%d"
).datatype – A string describing the expected data type (e.g.,
"<date>"
), shown in help messages.mincount – The minimum number of times the argument must appear (set to 0 for optional).
maxcount – The maximum number of times the argument can appear (controls memory allocation).
glossary – A short description of the argument for the glossary/help output. Pass
NULL
to omit.
- Returns:
If successful, returns a pointer to the allocated
arg_date_t
. ReturnsNULL
if there is insufficient memory.
Miscellaneous API¶
-
arg_rem_t *arg_rem(const char *datatype, const char *glossary)¶
Adds a remark or custom line to the syntax or glossary output.
The
arg_rem
function allows you to insert extra lines of text into the syntax or glossary output generated by Argtable3. Instead of embedding newline characters directly in your argument table strings—which can make the code messy—you can addarg_rem
structs to your argument table. These are dummy entries: they do not affect argument parsing, but theirdatatype
andglossary
strings are included in the output ofarg_print_syntax
andarg_print_glossary
.The name
arg_rem
stands for remark, inspired by theREM
statement in the BASIC programming language.For example, in the
mv
example program, we usearg_rem
to add additional lines for the-u|--update
option in the glossary:arg_lit_t *update = arg_litn("u", "update", 0, 1, "copy only when SOURCE files are"); arg_rem_t *update1 = arg_rem(NULL, " newer than destination files"); arg_rem_t *update1 = arg_rem(NULL, " or when destination files"); arg_rem_t *update2 = arg_rem(NULL, " are missing");
which will make the glossay look like:
-u, --update copy only when SOURCE files are newer than destination files or when the destination files are missing
We also use
arg_rem
to add a data type entry for the ordinary argument in the syntax:arg_rem_t *dest = arg_rem ("DEST|DIRECTORY", NULL);
which will make the syntax look like:
$ mv --help Usage: mv [-bfiuv] [--backup=[CONTROL]] [--reply={yes,no,query}] [--strip-trailing-slashes] [-S SUFFIX] [--target-directory=DIRECTORY] [--help] [--version] SOURCE [SOURCE]... DEST|DIRECTORY
- Parameters:
datatype – The data type or positional argument string to display in the syntax output, or NULL if not needed.
glossary – The remark or extra line to display in the glossary output, or NULL if not needed.
- Returns:
If successful, returns a pointer to the allocated
arg_rem_t
. Otherwise, returnsNULL
if there is insufficient memory available.