Hello friends
I am trying to implement command line options in a C Program. Please refer to the code below.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"open", required_argument, 0, 'o'}
};
void usage(FILE *file);
int main (int argc, char * argv[]) {
int i, ch, indexptr = 0;
opterr = 0;
while ((ch = getopt_long(argc, argv, "ho:", longopts, &indexptr)) != -1) {
switch(ch) {
case 'h':
usage(stdout);
exit(0);
break;
case 'o':
printf("Optarg file will be opened here\n");
break;
default:
printf("Didn't recognize that option. Try again\n");
exit(0);
}
}
argc -= optind;
argv += optind;
if(argc == 0){
fprintf(stderr,"ERROR: Required arguments missing. Please refer to the usage below: \n");
usage(stderr);
exit(1);
}
return 0;
}
void usage(FILE *file) {
if(file == NULL){
file = stdout;
}
fprintf(file,
"./program [OPTIONS] file.txt\n"
" --help \t Print this help screen\n"
" --open \t Open a file\n");
}
When I compile it and run,
for
it's not generating any errors.
But for
it's generating Segmentation fault. It is throwing up this error for --h, --he, --hel etc.,
Also, when I give, --open as the option, it's not even recognizing this.
I took a look at the manual of getopts_long but couldn't identify the problem.
Can somebody point out the mistake?
Thanks in advance.