Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- macro version of getopt()
- toggles:
- -vkeq | -v -k -e -q # or any other order
- arguments:
- -p ARG | -vkeqp ARG | -pARG | -vkeqpARG
- additional macros can be added too, to
- conveniently get optional arguments, or to get a variable amount of arguments.
- the final syntax feels like an interpreted language :D
- */
- #ifndef OPT_C
- #define OPT_C
- //specify option requires argument
- #define require \
- optarg = opt_pointer + 1; \
- if (*optarg == '\0') \
- { \
- if (++optind == argc) \
- goto opt_err_arg; \
- else \
- optarg = argv[optind]; \
- } \
- opt_pointer = opt_null_terminator;
- //start processing argv
- #define opt \
- int optind = 1; \
- char *opt_pointer = argv[1]; \
- char *optarg = NULL; \
- char opt_null_terminator[2] = {'\0','\0'}; \
- if (0) \
- { \
- opt_err_arg: \
- fprintf(stderr,"option %c requires argument.\n",*opt_pointer); \
- return 1; \
- opt_err_opt: \
- fprintf(stderr,"option %c is invalid.\n",*opt_pointer); \
- return 1; \
- } \
- for (; optind < argc; opt_pointer = argv[++optind]) \
- if (*opt_pointer++ == '-') \
- { \
- for (;;++opt_pointer) \
- switch (*opt_pointer) \
- {
- //stop processing argv
- #define done \
- default: \
- if (*opt_pointer != '\0') \
- goto opt_err_opt; \
- else \
- goto opt_next; \
- break; \
- } \
- opt_next:; \
- }
- #endif
- #include <stdio.h>
- int
- main (int argc, char **argv)
- {
- opt
- case 'h':
- puts ("Help");
- break;
- case 'v':
- puts ("Version");
- break;
- case 'f':require
- puts (optarg);
- break;
- done
- else puts (argv[optind]); //any non-option arguments
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement