fork(1) download
  1. #include <getopt.h>
  2. #include <cstdlib>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. void help (char ** argv)
  7. {
  8. cout << "`" << argv[0] << "` experiments with long options." << endl;
  9. }
  10.  
  11. void parse_args (int argc, char ** argv, int & verbose, int & param)
  12. {
  13. int c = 0;
  14. while (1)
  15. {
  16. static struct option long_options[] =
  17. {
  18. {"help", no_argument, 0, 'h'},
  19. {"verbose", required_argument, 0, 'v'},
  20. {"param", required_argument, 0, 0}
  21. };
  22. int option_index = 0;
  23. c = getopt_long (argc, argv, "hv:",
  24. long_options, &option_index);
  25. cout << "c=" << c << endl;
  26. if (c == -1)
  27. break;
  28. switch (c)
  29. {
  30. case 0:
  31. if (long_options[option_index].flag != 0)
  32. break;
  33. printf ("option %s", long_options[option_index].name);
  34. if (optarg)
  35. printf (" with arg %s", optarg);
  36. printf ("\n");
  37. break;
  38. case 'h':
  39. help (argv);
  40. exit (0);
  41. case 'v':
  42. verbose = atoi(optarg);
  43. break;
  44. case 'param':
  45. param = atoi(optarg);
  46. break;
  47. case '?':
  48. abort ();
  49. default:
  50. abort ();
  51. }
  52. }
  53. }
  54.  
  55. int main (int argc, char ** argv)
  56. {
  57. int verbose = 0;
  58. int param = 0;
  59. parse_args (argc, argv, verbose, param);
  60. cout << "verbose=" << verbose << " param=" << param << endl;
  61. return EXIT_SUCCESS;
  62. }
  63.  
Success #stdin #stdout 0.01s 2728KB
stdin
-v 2
stdout
c=-1
verbose=0 param=0