Case
2001-11-25 03:47:46
Category: c:runtime
Description: Example of using switch() and case to filter out the args given to main()
Author: detour
Viewed: 1789
Rating: (0 votes)


/* case.c written by detour@metalshell.com
 *
 * Example of using switch() and case to filter out the args
 * given to main()
 *
 * http://www.metalshell.com/
 *
 */
 
#include <stdio.h>
 
void pHelp(char *me);
 
int main(int argc, char *argv[]) {
  int x;
 
  /* If they gave no arguments */
  if(argc < 2) {
    pHelp(argv[0]);
    exit(1);
  } 
 
  for(x=1;x<argc;x++) {
 
    if(argv[x][0] == '-') {
 
      switch( argv[x][1] ) {
        case 'h':
        {
          pHelp(argv[0]);
      break;
        }
        case 'a':
        {
          printf("Hello\n");
          break;
        }
        case 'b':
        {
          printf("Goodbye\n");
          break;
        }
        /* Catches anything not picked up by case */
        default:
          printf("Unknown Option %s\n", argv[x]);
      }
 
    }
 
  }
}
 
/* Help Screen */
void pHelp(char *me) {
    printf("Usage %s [OPTION]\n\n", me);
    printf("-h,\t\tprints this screen\n");
    printf("-a,\t\tprints HELLO and exits\n");
    printf("-b,\t\tprints GOODBYE and exits\n"); 
}