Arguments longs
From Tuxunix
Exemple d'exécution
[tuxedo@macMob:OPT] $./scanArgument -h scanArgument: invalid option -- h Usage: ./scanArgument [--config|-c] fichier [--daemon|--inetd] [--timeout|-t] 10 parametre incorrect [tuxedo@macMob:OPT] $./scanArgument -c /tmp/toto.cfg -t 70 --daemon config /tmp/toto.cfg, timeout 70, daemon : 1, inetd : 0 tuxedo@macMob:OPT] $./scanArgument --timeout 70 --inetd config /etc/toto.conf, timeout 70, daemon : 0, inetd : 1
Code
1.#include <stdio.h> 2.#include <fcntl.h> 3.#include <stdlib.h> 4.#include <getopt.h> 5. 6.int flag=0; 7.int fd; 8. 9.int main(int argc, char *argv[]){ 10. 11. int option; 12. char *config="/etc/toto.conf"; 13. int timeout = 10; 14. int valDaemon=0; 15. int valInetd=0; 16. 17. char *optStr ="c:t:d:i:"; 18. 19.static struct option longopts[] = { 20./* name arg flag val*/ 21. {"config", 1, NULL, 'c'}, 22. {"timeout", 1, NULL, 't'}, 23. {"daemon", 0, NULL, 'd'}, 24. {"inetd", 0, NULL, 'i'}, 25. {NULL, 0, NULL, 0}, 26.}; 27. 28.while((option = getopt_long(argc, argv, optStr, longopts, NULL)) != -1){ 29. switch(option){ 30. case 'c' : 31. config=optarg; 32. break; 33. case 't' : 34. if (sscanf(optarg, "%d", &timeout) != 1){ 35. fprintf(stderr, "Erreur valeur timeout\n"); 36. } 37. break; 38. case 'd' : 39. valDaemon=1; 40. break; 41. case 'i' : 42. valInetd=1; 43. break; 44. case 0 : 45. break; 46. case '?' : 47. fprintf(stdout, "Usage: %s [--config|-c] fichier [--daemon|--inetd] [--timeout|-t] 10", argv[0]); 48. break; 49. } 50.} 51. 52.argc -= optind; 53.argv += optind; 54. 55.valDaemon != valInetd ? fprintf(stdout, "config %s, timeout %d, daemon : %d, inetd : %d\n", config, timeout, valDaemon, valInetd) : fprintf(stderr, "parametre incorrect\n"); 56. 57.return 0; 58. 59.} /*main*/

