Advertisement
Guest User

opt.c

a guest
Apr 28th, 2015
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. /*
  2.     macro version of getopt()
  3.     toggles:
  4.         -vkeq | -v -k -e -q # or any other order
  5.     arguments:
  6.         -p ARG | -vkeqp ARG | -pARG | -vkeqpARG
  7.    
  8.     additional macros can be added too, to
  9.     conveniently get optional arguments, or to get a variable amount of arguments.
  10.    
  11.     the final syntax feels like an interpreted language :D
  12. */
  13.  
  14. #ifndef OPT_C
  15. #define OPT_C
  16.  
  17. //specify option requires argument
  18. #define require \
  19.   optarg = opt_pointer + 1; \
  20.   if (*optarg == '\0') \
  21.   { \
  22.     if (++optind == argc) \
  23.       goto opt_err_arg; \
  24.     else \
  25.       optarg = argv[optind]; \
  26.   } \
  27.   opt_pointer = opt_null_terminator;
  28.  
  29. //start processing argv
  30. #define opt \
  31. int   optind                 = 1; \
  32. char *opt_pointer            = argv[1]; \
  33. char *optarg                 = NULL; \
  34. char  opt_null_terminator[2] = {'\0','\0'}; \
  35. if (0) \
  36. { \
  37.   opt_err_arg: \
  38.     fprintf(stderr,"option %c requires argument.\n",*opt_pointer); \
  39.     return 1; \
  40.   opt_err_opt: \
  41.     fprintf(stderr,"option %c is invalid.\n",*opt_pointer); \
  42.     return 1; \
  43. } \
  44. for (; optind < argc; opt_pointer = argv[++optind]) \
  45.   if (*opt_pointer++ == '-') \
  46.   { \
  47.     for (;;++opt_pointer) \
  48.       switch (*opt_pointer) \
  49.       {
  50.  
  51. //stop processing argv
  52. #define done \
  53.       default: \
  54.         if (*opt_pointer != '\0') \
  55.           goto opt_err_opt; \
  56.         else \
  57.           goto opt_next; \
  58.         break; \
  59.       } \
  60.     opt_next:; \
  61.   }  
  62. #endif
  63.  
  64. #include <stdio.h>
  65. int
  66. main (int argc, char **argv)
  67. {
  68.   opt
  69.   case 'h':
  70.     puts ("Help");
  71.     break;
  72.   case 'v':
  73.     puts ("Version");
  74.     break;
  75.   case 'f':require
  76.     puts (optarg);
  77.     break;
  78.   done
  79.   else puts (argv[optind]); //any non-option arguments
  80.  
  81.   return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement