Page 76 - C-Language
P. 76
const char *basename = strrchr(path, '/');
basename = basename ? basename + 1 : path;
fprintf (fp, "usage: %s [OPTION]\n", basename);
fprintf (fp, " -h, --help\t\t"
"Print this help and exit.\n");
fprintf (fp, " -f, --file[=FILENAME]\t"
"Write all output to a file (defaults to out.txt).\n");
fprintf (fp, " -m, --msg=STRING\t"
"Output a particular message rather than 'Hello world'.\n");
}
/* parse command-line options and print message */
int main(int argc, char *argv[])
{
/* for code brevity this example just uses fixed buffer sizes for strings */
char filename[256] = { 0 };
char message[256] = "Hello world";
FILE *fp;
int help_flag = 0;
int opt;
/* table of all supported options in their long form.
* fields: name, has_arg, flag, val
* `has_arg` specifies whether the associated long-form option can (or, in
* some cases, must) have an argument. the valid values for `has_arg` are
* `no_argument`, `optional_argument`, and `required_argument`.
* if `flag` points to a variable, then the variable will be given a value
* of `val` when the associated long-form option is present at the command
* line.
* if `flag` is NULL, then `val` is returned by `getopt_long` (see below)
* when the associated long-form option is found amongst the command-line
* arguments.
*/
struct option longopts[] = {
{ "help", no_argument, &help_flag, 1 },
{ "file", optional_argument, NULL, 'f' },
{ "msg", required_argument, NULL, 'm' },
{ 0 }
};
/* infinite loop, to be broken when we are done parsing options */
while (1) {
/* getopt_long supports GNU-style full-word "long" options in addition
* to the single-character "short" options which are supported by
* getopt.
* the third argument is a collection of supported short-form options.
* these do not necessarily have to correlate to the long-form options.
* one colon after an option indicates that it has an argument, two
* indicates that the argument is optional. order is unimportant.
*/
opt = getopt_long (argc, argv, "hf::m:", longopts, 0);
if (opt == -1) {
/* a return value of -1 indicates that there are no more options */
break;
}
switch (opt) {
case 'h':
/* the help_flag and value are specified in the longopts table,
https://riptutorial.com/ 52

