
#include "stdlib.h"
#include "stdio.h"
#include "getopt.h"
#include "string.h"
void print_help(int exval);
char program[100] = "sample";
int main(int argc, char *argv[]) {
int opt;
strcpy(program,argv[0]);
if (argc == 1) print_help(1);
while((opt = getopt(argc, argv, "hVvf:o:")) != -1) {
switch(opt) {
case 'h':
print_help(0);
break;
case 'V':
printf("%s", program);
exit(0);
break;
case 'v':
printf("%s: Verbose option is set '%c'\n", program, optopt);
break;
case 'f':
printf("%s: Filename %s\n", program, optarg);
break;
case 'o':
printf("Output: %s\n", optarg);
break;
case ':':
fprintf(stderr, "%s: Error - Option '%c' needs a value\n\n", program, optopt);
print_help(1);
break;
case '?':
fprintf(stderr, "%s: Error - No such option: '%c'\n\n", program, optopt);
print_help(1);
}
}
for(; optind < argc; optind++) printf("argument: %s\n", argv[optind]);
return 0;
}
// -----
void print_help(int exval) {
printf("Usage: %s [-h] [-V] [-f FILE] [-o FILE]\n\n", program);
printf(" -h print this help and exit\n");
printf(" -V print version and exit\n\n");
printf(" -v set verbose flag\n");
printf(" -f FILE set intput file\n");
printf(" -o FILE set output file\n\n");
exit(exval);
}