Created
February 7, 2024 21:45
-
-
Save jnbek/1b81efec8780fc1ff0f3fc9f844c9477 to your computer and use it in GitHub Desktop.
GetOpt Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
int | |
main (int argc, char **argv) | |
{ | |
int verbose = 0; | |
int help = 0; | |
char *file = NULL; | |
int index; | |
int c; | |
opterr = 0; | |
while ((c = getopt (argc, argv, "vhf:")) != -1) | |
switch (c) | |
{ | |
case 'v': | |
verbose = 1; | |
break; | |
case 'f': | |
file = optarg; | |
break; | |
case 'h': | |
help = 1; | |
printf("Options:\n"); | |
printf("-h Print this message\n"); | |
printf("-v Verbose output\n"); | |
printf("-f <filename> (Required) Filename to send output\n"); | |
return 0; | |
case '?': | |
if (optopt == 'f') | |
fprintf (stderr, "Option -%c requires an argument.\n", optopt); | |
else if (isprint (optopt)) | |
fprintf (stderr, "Unknown option `-%c'.\n", optopt); | |
else | |
fprintf (stderr, | |
"Unknown option character `\\x%x'.\n", | |
optopt); | |
return 1; | |
default: | |
abort (); | |
} | |
printf ("verbose = %d, file = %s, help = %d\n", | |
verbose, file, help); | |
for (index = optind; index < argc; index++) | |
printf ("Non-option argument %s\n", argv[index]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment