Skip to content

Instantly share code, notes, and snippets.

@AlexsJones
Created June 1, 2012 09:50
Show Gist options
  • Select an option

  • Save AlexsJones/2850845 to your computer and use it in GitHub Desktop.

Select an option

Save AlexsJones/2850845 to your computer and use it in GitHub Desktop.
Getopt in C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#define PARAMLEN 2
void print_params(void)
{
printf("Please enter the correct parameters...\n");
printf("-f %3d Specify a folder to search...\n");
printf("-e %3d Specify an extension type to search...\n");
}
int read_input(int argc,char **argv)
{
int c;
int fflag = 0;
int eflag = 0;
char *fvalue = NULL;
char *evalue = NULL;
while((c = getopt(argc,argv,"f:e:")) != -1)
{
switch(c)
{
case 'f':
fflag =1;
fvalue = optarg;
break;
case 'e':
eflag =1;
evalue = optarg;
break;
case '?':
if(optopt == 'f')
{
fprintf(stderr,"Option -%c requires an argument...\n",optopt);
}
if(optopt == 'e')
{
fprintf(stderr,"Option -%c requires an argument...\n",optopt);
}
if (isprint (optopt))
{
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
print_params();
}
else
{
fprintf (stderr,"Unknown option character `\\x%x'.\n", optopt);
print_params();
}
}
}
printf("fflag is %d with value of %s, eflag is %d with value of %s\n",fflag,fvalue,eflag,evalue);
return 0;
}
int main(int argc,char **argv)
{
read_input(argc,argv);
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment