i use this template from here . Example of Getopt - The GNU C Library there is a long option also.
this little program is how i would have done it as a hello world program but i am not sure if there is not a better more nice way of using it. i am still new to this.
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void PrintUsage(const char *progname);
void fcopy(FILE *in,FILE *out);
int main (int argc, char **argv)
{
int aflg = 0;
int bflg = 0;
char *cval = NULL;
int index;
int c;
const char *progname=argv[0];
opterr = 0;
FILE *fp;
while ((c = getopt (argc, argv, "abc:")) != -1)
{ switch (c)
{
case 'a': aflg = 1; break;
case 'b': bflg = 1; break;
case 'c': cval = optarg; break;
case '?':
if (optopt == 'c')
{
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);
exit(EXIT_FAILURE);
}
default:
abort ();
}
}
if(aflg)
for (index = optind; index < argc; index++)
{
fprintf(stdout,"Non-option argument %s\n", argv[index]);
exit(0);
}
else if(bflg)
{
fprintf(stdout,"aflag = %d, bflag = %d, cvalue = %s\n",
aflg, bflg, cval);
exit(0);
}
else if(cval != NULL)
{
printf("opening file %s \n",cval);
if((fp=fopen(cval,"r")) == NULL)
{
exit(1);
}
else
{
fcopy(fp,stdout);
exit(EXIT_SUCCESS);
}
}
else
{
fprintf(stdout,"%s executing :no options\n",progname);
}
return 0;
}
void PrintUsage(const char *progname)
{
fprintf(stdout,"USAGE:%s [options]\n"
"barebones usage help text\n",
progname);
}
void fcopy(FILE *in,FILE *out)
{
int c;
while((c=getc(in)) != EOF)
fprintf(out,"%c",c);
}
option a shows arguments giving
option b shows what flags status is
option c needs as argument which is on thsi case teh file name to open and display on screen.
i made the example slight modified from the page i linked to and use it as a template in my editor.-
ps:sorry if the indent goes when i post. i have indented before i posted. i hope it is working.