You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
box-o-sand/gnu-c/getopt-example.c

55 lines
1.1 KiB

/*
* Example getopt usage mostly from getopt(3)
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <libgen.h>
void die_usage(char *prog, char *msg) {
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n", prog);
if (msg != NULL) {
fprintf(stderr, "%s\n", msg);
}
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
char *prog;
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
prog = basename(argv[0]);
while ((opt = getopt(argc, argv, "hnt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
case 'h':
default: /* '?' */
die_usage(prog, NULL);
}
}
printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc) {
die_usage(prog, "Expected argument after options");
}
printf("name argument = %s\n", argv[optind]);
printf("nsecs = %d\n", nsecs);
exit(EXIT_SUCCESS);
}