Problème d'ordre avec getopt
Bonjour à tous,
Je dois traiter les arguments de mon programme. Pour cela, j'utilisa la fonction getopt.
Voici comment comment lancer mon programme :
Code:
tftp ip port [-b blksize] [-w windowsize] src_file dest_file
Donc avant les options, j'ai des arguments comme une adresse IP et un port. Apès mes options, j'ai deux noms de fichier.
Le problème c'est que mes options doivent être en premier et ensuite mes arguments (qui ne sont pas des options) pour que cela marche. Si j'intercale des options avec des arguments, getopt ignores les options. Exemple :
Code:
tftp -b 1024 -w 5 localhost 25565 fichier1 fichier2
marche correctement, mais :
Code:
tftp localhost 25565 -b 1024 -w 5 fichier1 fichier2
ne fonctionne pas, getopt ne retourne rien.
Voici mon code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| int main(int argc, char **argv) {
int ch;
while ((ch = getopt(argc, argv, "b:w:")) != -1) {
switch (ch) {
case 'b':
printf("blksize: %s\n", optarg);
break;
case 'w':
printf("blksize: %s\n", optarg);
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
for (; optind < argc; ++optind) {
printf ("argv[%d] : %s\n", optind, argv[optind]);
}
return EXIT_SUCCESS;
} |
Pouvez-vous m'aider ?
Merci :)
EDIT
Bon alors j'ai réussi à obtenir ce que je voulais, mais je trouve la solution très sale. L'idée c'est de récupérer l'IP et le port, puis récupérer les options et enfin, récupérer le fichier source et le fichier de destination. Voici le code :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| // Récupère l'adresse IP et le port
char *ip, *port;
ip = argv[1];
if (ip == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
port = argv[2];
if (port == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
// Récupère les options
int ch;
char *blksize, *windowsize;
optind += 2;
while ((ch = getopt(argc, argv, "b:w:")) != -1) {
switch (ch) {
case 'b':
blksize = optarg;
break;
case 'w':
windowsize = optarg;
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
// Récupère le nom du fichier source et de destination
char *file_src, *file_dest;
file_src = argv[optind];
if (file_src == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
file_dest = argv[optind + 1];
if (file_dest == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
// Affiche les arguments
printf("ip: %s\n", ip);
printf("port: %s\n", port);
if (blksize != NULL) {
printf("blksize: %s\n", blksize);
}
if (windowsize != NULL) {
printf("windowsize: %s\n", windowsize);
}
printf("file src: %s\n", file_src);
printf("file_dest: %s\n", file_dest); |