Posted By

dzone on 01/24/09


Tagged

parse input arguments Getopt


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

dzone
tandouri
skammer


Using getopt() to parse input arguments in C


 / Published in: C
 

URL: http://snippets.dzone.com/posts/show/6850

This is a simple bit of code to show how you can use the "getopt()" function to parse input arguments without headaches.

  1. void print_help()
  2. {
  3. printf("usage:\n") ;
  4. printf("\t\t-i set input file\n") ;
  5. printf("\t\t-o set output file\n") ;
  6. printf("\t\t-c set config file\n") ;
  7. printf("\t\t-h print this help information\n") ;
  8. printf("\t\t-v print version\n") ;
  9. }
  10. char* input_file = NULL ;
  11. char *query=NULL;
  12. char opt_char=0;
  13. while ((opt_char = getopt(argc, argv, "i:q:vh")) != -1)
  14. {
  15. switch(opt_char)
  16. {
  17. case 'h':
  18. print_help();
  19. exit(-1);
  20. break;
  21. case 'v':
  22. print_version() ;
  23. exit(-1) ;
  24. break ;
  25. case 'i':
  26. input_file= optarg ;
  27. break ;
  28. case 'q':
  29. query= optarg ;
  30. break ;
  31. default:
  32. print_help();
  33. exit(-1);
  34. break;
  35. }
  36. }

Report this snippet  

You need to login to post a comment.