getopt_exo.c
00001 #include <stdio.h>
00002 #include <getopt.h>
00003 #include <string.h>
00004 #include <stdlib.h>
00005 #include <assert.h>
00006
00007 #define STR_MAX_SIZE 256 // taille maximale tolérée pour les chaînes de caractères
00008
00009
00010 void printError(char * msg) {
00011 fprintf(stderr, "[ERREUR] %s\n",msg);
00012 exit(EXIT_FAILURE);
00013 }
00014
00015 void usage(char * command) {
00016 printf("%s [-i val_i] [-f val_f] [-s string] [-k key] [-h] file\n", command);
00017 exit(EXIT_SUCCESS);
00018 }
00019
00020 int main(int argc, char * argv[])
00021 {
00022 extern char *optarg;
00023 extern int optind;
00024 char c;
00025
00026 int opt_i = 14;
00027 float opt_f = 1.5;
00028 char opt_s[STR_MAX_SIZE] = "On est super content!";
00029 unsigned long opt_k = 0x90ABCDEF;
00030 char input_file[STR_MAX_SIZE];
00031
00032 while ((c = getopt(argc, argv, "i:f:s:k:h")) != -1) {
00033 if ((optarg != NULL) && (optarg[0] == '-')) printError("Mauvais format");
00034 switch(c) {
00035 case 'h': usage(argv[0]); return EXIT_SUCCESS;
00036 case 'i':
00037 opt_i = (int) strtol(optarg, NULL, 10);
00038 break;
00039 case 'f':
00040 opt_f = (float) strtod(optarg, NULL);
00041 break;
00042 case 's':
00043 assert(strlen(optarg) < STR_MAX_SIZE);
00044 strncpy(opt_s, optarg, STR_MAX_SIZE);
00045 break;
00046 case 'k':
00047 opt_k = (unsigned long) strtol(optarg, NULL, 16);
00048 break;
00049 default: printError("option non reconnue!");
00050 }
00051 }
00052 if ((argc - optind) != 1) printError("l'argument file est obligatoire!");
00053
00054 assert(strlen(argv[optind]) < STR_MAX_SIZE);
00055 strncpy(input_file, argv[optind], STR_MAX_SIZE);
00056
00057
00058 printf("opt_i : %d\n", opt_i);
00059 printf("opt_f : %f\n", opt_f);
00060 printf("opt_s : %s\n", opt_s);
00061 printf("opt_k : %lx\n", opt_k);
00062 printf("input_file : %s\n", input_file);
00063 return 0;
00064 }