diff --git a/Makefile b/Makefile index 8da76e15e43e72ee30f051a0681d2839fd7adaa7..9f5a7173d833419d26e0f9eda0665c0e62c3aa56 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ HTMLOPTIONS += -t html5 HTMLOPTIONS += -c css/tufte-css/tufte.css HTMLOPTIONS += --self-contained -all: strings.pdf tests_assertions.pdf make.pdf base_3.pdf base_2.pdf base_1.pdf intro.pdf index.html +all: ligne_commande.pdf strings.pdf tests_assertions.pdf make.pdf base_3.pdf base_2.pdf base_1.pdf intro.pdf index.html intro.pdf: intro.md metadata.yaml pandoc $(PDFOPTIONS) -o $@ $^ @@ -42,6 +42,9 @@ tests_assertions.pdf: tests_assertions.md metadata.yaml strings.pdf: strings.md metadata.yaml pandoc $(PDFOPTIONS) -o $@ $^ +ligne_commande.pdf: ligne_commande.md metadata.yaml + pandoc $(PDFOPTIONS) -o $@ $^ + index.html: index.md pandoc -s $(OPTIONS) $(HTMLOPTIONS) -o $@ $< diff --git a/ligne_commande.md b/ligne_commande.md new file mode 100644 index 0000000000000000000000000000000000000000..b83658bf23207aa775e338c2ac34140ad065006a --- /dev/null +++ b/ligne_commande.md @@ -0,0 +1,83 @@ +% La ligne de commande +% Inspirés des slides de F. Glück +% 16 octobre 2019 + +# Point d'entrée d'un programme + +- Le point d'entrée est la fonction `main()`{.C}. +- Elle peut être déclarée de 4 façon différentes: + 1. `void main()`{.C}. + 2. `int main()`{.C}. + 3. `void main(int argc, char **argv)`{.C}. + 4. `int main(int argc, char **argv)`{.C}. + +- `argc`{.C} est le nombre d'arguments passés à la ligne de commade: **le premier est celui du programme lui-même**. +- `argv`{.C} est un tableau de chaînes de caractères passés sur la ligne de commande. + +# Exemple d'utilisation + +Pour la fonction dans le programme `prog` + +```C +int main(int argc, char **argv) +``` + +Pour l'exécution suivante on a + +```bash +$ ./prog -b 50 file.txt +``` + +```C +argc == 4 +argv[0] == "prog" +argv[1] == "-b" +argv[2] == "50" +argv[3] == "file.txt" +``` + +# Conversion des arguments + +- Les arguments sont toujours stockés comme des **chaînes de caractère**. +- Peu pratique si on veut manipuler des valeurs numériques. +- Fonctions pour faire des conversions: + + ```C + int atoi(const char *nptr); + long atol(const char *nptr); + long long atoll(const char *nptr); + double atof(const char *nptr); + int snprintf(char *str, size_t size, + const char *format, ...); + // str: buffer, size: taille en octets max à copier, + // format: cf printf(), ret: nombre de char lus + ``` + +# Exemple d'utilisation + +\footnotesize + +```C +#include <stdio.h> +#include <stdlib.h> +#include <libgen.h> + +int main(int argc, char **argv) { + if (argc != 3) { + char *progname = basename(argv[0]); + fprintf(stderr, "usage: %s name age\n", progname); + return EXIT_FAILURE; + } + + char *name = argv[1]; + int age = atoi(argv[2]); + + printf("Hello %s, you are %d years old.\n", name, age); + return EXIT_SUCCESS; +} +``` + +```bash +$ ./prog Paul 29 +Hello Paul, you are 29 years old. +``` \ No newline at end of file