Posted By

tandouri on 08/21/09


Tagged

command line cmd parsing Getopt


Versions (?)

getopt example


 / Published in: C
 

  1. int parseCMD(int argc, char** argv)
  2.  
  3. {
  4. /* variables for getopt*/
  5. int c;
  6. int index;
  7.  
  8. /* configs for cmd-args*/
  9. int aflag = 0;
  10. int bflag = 0;
  11. char *cvalue = NULL;
  12.  
  13. /* this is where the magic happens*/
  14. opterr = 0;
  15.  
  16. while ((c = getopt (argc, argv, "xbc:")) != -1) {
  17. switch (c)
  18. {
  19. case 'x':
  20. aflag = 1;
  21. break;
  22. case 'b':
  23. bflag = 1;
  24. break;
  25. case 'c':
  26. cvalue = optarg;
  27. break;
  28. case '?':
  29. if (optopt == 'c') {
  30. fprintf (stderr, "Option -%c requires an argument.\n", optopt);
  31. } else if (isprint (optopt)) {
  32. fprintf (stderr, "Unknown option `-%c'.\n", optopt);
  33. } else {
  34. fprintf (stderr,
  35. "Unknown option character `\\x%x'.\n",
  36. optopt);
  37. }
  38. return -1;
  39. default:
  40. abort ();
  41. }
  42. }
  43.  
  44. /* check what was recognized */
  45. printf ("aflag = %d, bflag = %d, cvalue = %s\n",
  46. aflag,
  47. bflag,
  48. cvalue);
  49.  
  50. /* error if argument not found */
  51. for (index = optind; index < argc; index++) {
  52. printf ("Non-option argument %s\n", argv[index]);
  53. }
  54.  
  55. return 0;
  56. }

Report this snippet  

You need to login to post a comment.