Skip to content

Instantly share code, notes, and snippets.

@jnbek
Created February 7, 2024 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnbek/1b81efec8780fc1ff0f3fc9f844c9477 to your computer and use it in GitHub Desktop.
Save jnbek/1b81efec8780fc1ff0f3fc9f844c9477 to your computer and use it in GitHub Desktop.
GetOpt Example
#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