- trixie 4.27.0-1
- trixie-backports 4.30.0-1~bpo13+2
- testing 4.30.0-1
- unstable 4.30.0-1
| getopt(3) | Library Functions Manual | getopt(3) |
NOM¶
getopt, optarg, optind, opterr, optopt - Parse command-line options
BIBLIOTHÈQUE¶
Bibliothèque C standard (libc, -lc)
SYNOPSIS¶
#include <unistd.h>
int getopt(int argc, char *argv[],
const char *chaine_options);
extern char *optarg; extern int optind, opterr, optopt;
getopt() :
_POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
DESCRIPTION¶
La fonction getopt() analyse les arguments de la ligne de commande. Ses arguments argc et argv correspondent au nombre et à la table d'éléments qui sont transmis à la fonction main() lors du lancement du programme. Un élément de argv qui commence par « - » (et qui n'est pas uniquement « -- » ou « - ») est considéré comme une option. Les caractères à la suite du ou des « - » initiaux sont les caractères de l'option. Si getopt() est appelée à plusieurs reprises, elle renverra successivement chaque caractère de chaque option.
La variable optind est l'index de l'élément suivant à analyser dans argv. Le système initialise cette valeur à 1. L'appelant peut la remettre à 1 pour recommencer l'analyse du même tableau de paramètres argv ou pour en analyser un nouveau.
Si getopt() trouve un autre caractère d'option, elle renvoie ce caractère en mettant à jour la variable externe optind et la variable statique nextchar, de façon à ce que l'appel suivant à getopt() puisse continuer l'analyse avec le caractère d'option suivant ou l'élément suivant de argv.
S'il n'y a plus de caractères d'option, getopt() renvoie -1. Alors, optind devient l'index du premier élément de argv qui n'est pas une option.
chaine_options est une chaîne contenant l'ensemble des caractères d'option autorisés. Un caractère d'option autorisé est un caractère ascii(7) imprimable sur 1 octet (pour lequel isgraph(3) renverrait une valeur différente de zéro) autre que « - », « : » ou « ; ». Si un de ces caractères est suivi par un deux-points (« : »), l'option nécessite un argument, donc getopt() placera dans optarg un pointeur sur le texte suivant dans le même élément de argv ou sur le texte de l'élément de argv suivant. Un double deux-points (« :: ») signifie qu'une option prend un argument facultatif. S'il existe un texte dans le même élément de argv (c'est-à-dire dans le même mot que le nom de l'option elle-même comme « -oarg »), il est renvoyé dans optarg, sinon optarg est défini à zéro. Il s'agit d'une extension GNU. Si chaine_options contient W suivi d'un point-virgule, -W foo est traité comme l'option longue --foo (l'option -W est réservée par POSIX.2 pour des extensions spécifiques à l'implémentation). Ce comportement, spécifique à la version GNU, est pris en charge à partir de la version 2 de la bibliothèque glibc.
By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end. Two other scanning modes are also implemented. If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered. If '+' is not the first character of optstring, it is treated as a normal option. If POSIXLY_CORRECT behavior is required in this case optstring will contain two '+' symbols. If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) The special argument "--" forces an end of option-scanning regardless of the scanning mode.
getopt() peut détecter deux types d'erreur lors du traitement de la liste d'options : (1) un caractère d'option non spécifié dans chaine_options et (2) un argument d'option manquant (c'est-à-dire une option sans son argument attendu à la fin de la ligne de commande). Les erreurs de ce type sont traitées et signalées comme suit :
- Par défaut, getopt() affiche un message d'erreur sur la sortie d'erreur standard, place le caractère d'option erroné dans optopt et renvoie « ? » comme résultat.
- Si l'appelant a défini la variable globale opterr à zéro, getopt() n'affiche pas de message d'erreur. L'appelant peut détecter la présence d'une erreur en vérifiant si la fonction a renvoyé « ? » (par défaut, opterr possède une valeur différente de zéro).
- Si le premier caractère de chaine_options (suivant un des caractères facultatifs « + » ou « - » décrits ci-dessus) est un « : », là non plus, getopt() n'affiche pas de message d'erreur. En outre, elle renvoie « : » au lieu de « ? » pour indiquer un argument d'option manquant, ce qui permet à l'appelant de distinguer les deux types d'erreur.
VALEUR RENVOYÉE¶
Si une option a été trouvée, getopt() renvoie le caractère de l'option. Si toutes les options de la ligne de commande ont été lues, getopt() renvoie -1. Si getopt() rencontre un caractère d'option qui n'est pas dans chaine_options, « ? » est renvoyé. Si getopt() rencontre une option avec un argument manquant, la valeur renvoyée dépend du premier caractère de chaine_options : si c'est « : », ce caractère est renvoyé, sinon « ? » est renvoyé.
ENVIRONNEMENT¶
- POSIXLY_CORRECT
- Si cette variable est définie, l'analyse s'arrête dès qu'un argument ne constituant pas une option est rencontré.
ATTRIBUTS¶
Pour une explication des termes utilisés dans cette section, consulter attributes(7).
| Interface | Attribut | Valeur |
| getopt() | Sécurité des threads | MT-Unsafe race:getopt env |
VERSIONS¶
POSIX specifies that the argv array argument should be const, but these functions permute its elements unless the environment variable POSIXLY_CORRECT is set. const is used in the actual prototype to be compatible with other systems; however, this page doesn't show the qualifier, to avoid confusing readers.
NORMES¶
- getopt()
- POSIX.1-2008.
- L'utilisation de « + » et « - » dans chaine_options est une extension GNU.
HISTORIQUE¶
- getopt()
- POSIX.1-2001 et POSIX.2.
Sur certaines anciennes implémentations, getopt() était déclarée dans <stdio.h>. SUSv1 permettait que la déclaration apparaisse soit dans <unistd.h>, soit dans <stdio.h>. POSIX.1-1996 considère la déclaration dans <stdio.h> comme « LEGACY » (obsolète), et POSIX.1-2001 n'exige pas que la déclaration soit dans <stdio.h>.
Very old versions of glibc were affected by a _PID_GNU_nonoption_argv_flags_ environment variable.
NOTES¶
A program that scans multiple argument vectors, or rescans the same vector more than once, and wants to make use of GNU extensions such as '+' and '-' at the start of optstring, or changes the value of POSIXLY_CORRECT between scans, must reinitialize getopt() by resetting optind to 0, rather than the traditional value of 1. (Resetting to 0 forces the invocation of an internal initialization routine that rechecks POSIXLY_CORRECT and checks for GNU extensions in optstring.)
Les arguments de la ligne de commande sont analysés selon leur ordre strict, ce qui signifie qu'une option nécessitant un argument va consommer l'argument suivant, qu'il s'agisse de son argument correctement spécifié ou de l'option suivante (auquel cas l'utilisateur aura mal rédigé la ligne de commande). Par exemple, si chaine_options contient « 1n: » et si l'utilisateur fournit une ligne de commande incorrecte en spécifiant prog -n -1, l'option -n se verra affecter la valeur de optarg « -1 », et l'option -1 sera considérée comme non spécifiée.
EXEMPLES¶
getopt()¶
The following trivial example program uses getopt() to handle two program options: -n, with no associated value; and -t val, which expects an associated value.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage : %s [-t nsecs] [-n] nom\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n",
flags, tfnd, nsecs, optind);
if (optind >= argc) {
fprintf(stderr, "Argument requis après les options\n");
exit(EXIT_FAILURE);
}
printf("argument nom = %s\n", argv[optind]);
/* Le reste du code n'est pas mentionné */
exit(EXIT_SUCCESS);
}
VOIR AUSSI¶
getopt(1), getopt_long(3), getopt_long_only(3), getsubopt(3)
TRADUCTION¶
La traduction française de cette page de manuel a été créée par Christophe Blaess <https://www.blaess.fr/christophe/>, Stéphan Rafin <stephan.rafin@laposte.net>, Thierry Vignaud <tvignaud@mandriva.com>, François Micaux, Alain Portal <aportal@univ-montp2.fr>, Jean-Philippe Guérard <fevrier@tigreraye.org>, Jean-Luc Coulon (f5ibh) <jean-luc.coulon@wanadoo.fr>, Julien Cristau <jcristau@debian.org>, Thomas Huriaux <thomas.huriaux@gmail.com>, Nicolas François <nicolas.francois@centraliens.net>, Florentin Duneau <fduneau@gmail.com>, Simon Paillard <simon.paillard@resel.enst-bretagne.fr>, Denis Barbier <barbier@debian.org>, David Prévot <david@tilapin.org> et Lucien Gentis <lucien.gentis@waika9.com>
Cette traduction est une documentation libre ; veuillez vous reporter à la GNU General Public License version 3 concernant les conditions de copie et de distribution. Il n'y a aucune RESPONSABILITÉ LÉGALE.
Si vous découvrez un bogue dans la traduction de cette page de manuel, veuillez envoyer un message à debian-l10n-french@lists.debian.org.
| 8 février 2026 | Pages du manuel de Linux 6.17 |