83
Universit´ e de Metz T.P. Langage C /C++ Licence EEA Ann´ ee Universitaire 2003/2004 Yann MOR ` ERE

TP Langage C/C++

  • Upload
    dinhdat

  • View
    254

  • Download
    7

Embed Size (px)

Citation preview

Universite de Metz

T.P. Langage C/C++

Licence EEA

Annee Universitaire 2003/2004

Yann MORERE

2 TPs de Langage C/C++

Cette serie de TPs a pour objectif de vous faire coder et utiliser le langage C et C++. Il s’agira detranscrire sous la forme d’un programme C ou C++, des algorithmes afin de realiser les fonctionsdemandees. Tous les TPs s’effectueront sous le systeme d’exploitation GNU/Linux.

Table des matieres

Demarrage Unix & GNU/Linux 71 Procedure de Login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

1.1 Remarque sur le mot de passe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.2 Pour changer de mot de passe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3 Terminer votre session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 Forme et validation d’une commande . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Commande importante : man . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Les editeurs de texte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

4.1 vi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.1.1 Mode saisie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.1.2 Mode commande . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.3 Deplacement du curseur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.4 Commandes d’effacement et remise de texte . . . . . . . . . . . . . . . . . . . . . . 124.1.5 Insertion d’un fichier exterieur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.6 Annulation de la derniere commande . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.7 Recherche et remplacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.8 Deplacement de texte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.1.9 Mode execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4.2 emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.2.1 Les modes d’edition d’emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.2.2 Notion de buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.3 Commande de deplacement du curseur . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.4 Insertion et suppression de texte . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.5 Edition simultanee de plusieurs fichiers . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.6 Recherche et remplacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.7 Insertion d’un fichier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144.2.8 Suppression de fenetres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.2.9 Sauvegarder et quitter emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4.3 nedit, gedit, gnotepad & kedit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Compiler et Automatiser les taches : make . . . . . . . . . . . . . . . . . . . . . . . . . 17

5.1 Que fait make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.2 Dans le vif du sujet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.3 Pourquoi passer par make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.4 Plus loin avec GNU Make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.5 Nouvelles regles predefinies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.6 make all, installation et nettoyage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195.7 Compiler du C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Sujets de TPs 21TP C N 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Polynome du second degres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Changement de Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Les nombres complexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23TP C N 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Les tableaux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2510 Traitement de chaınes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2511 Le Verlan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2612 Les palindromes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26TP C N 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 3

13 Resolution d’une equation f(x) = 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2713.1 Dichotomie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2713.2 Interpolation Lineaire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2813.3 Newton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2813.4 Travail demande . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

14 Calcul integrale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2914.1 La methode des rectangles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2914.2 La methode du point median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2914.3 La methode des trapezes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3014.4 La methode de Simpson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3014.5 Travail demande . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Annexes Utiles 33

Memento des commandes du shell 35Memento des commandes du shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

A.1 Diffusion du present document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37A.2 Gestion des utilisateurs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37A.3 Gestion des fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38A.4 Recherche et archivage de fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38A.5 Gestion des processus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39A.6 Traitement de chaınes de caracteres (pour programmation shell) . . . . . . . . . . . . 39A.7 Flux de texte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39A.8 Autres outils de traitement du texte . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Librairies standards C 41Standard C Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

B.1 clearerr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43B.2 fclose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.3 feof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.4 ferror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.5 fflush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.6 fgetc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44B.7 fgetpos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45B.8 fgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45B.9 fopen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45B.10 fprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45B.11 fputc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46B.12 fputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46B.13 fread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46B.14 freopen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46B.15 fscanf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47B.16 fseek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47B.17 fsetpos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47B.18 ftell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47B.19 fwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47B.20 getc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48B.21 getchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48B.22 gets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48B.23 perror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48B.24 printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48B.25 putc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49B.26 putchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50B.27 puts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50B.28 remove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Yann MORERE Licence E.E.A. Universite de Metz

4 TPs de Langage C/C++

B.29 rename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50B.30 rewind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51B.31 scanf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51B.32 setbuf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51B.33 setvbuf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51B.34 sprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52B.35 sscanf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52B.36 tmpfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52B.37 tmpnam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52B.38 ungetc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52B.39 vprintf, vfprintf, and vsprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Standard C string and character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55C.1 atof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55C.2 atoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56C.3 atol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56C.4 isalnum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56C.5 isalpha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56C.6 iscntrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57C.7 isdigit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57C.8 isgraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57C.9 islower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57C.10 sprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57C.11 ispunct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58C.12 isspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58C.13 isupper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58C.14 isxdigit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58C.15 memchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58C.16 memcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59C.17 memcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59C.18 memmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59C.19 memset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59C.20 strcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59C.21 strchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60C.22 strcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60C.23 strcoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60C.24 strcpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60C.25 strcspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60C.26 strerror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61C.27 strlen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61C.28 strncat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61C.29 strncmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61C.30 strncpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61C.31 strpbrk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.32 strrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.33 strspn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.34 strstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.35 strtod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.36 strtok . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62C.37 strtol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63C.38 strtoul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63C.39 strxfrm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63C.40 tolower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63C.41 toupper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Standard C Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65D.1 abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65D.2 acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65D.3 asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66D.4 atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 5

D.5 atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66D.6 ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66D.7 cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66D.8 cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66D.9 div . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67D.10 exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67D.11 fabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67D.12 floor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67D.13 fmod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67D.14 frexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68D.15 labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68D.16 ldexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68D.17 ldiv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68D.18 log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68D.19 log10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.20 modf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.21 pow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.22 sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.23 sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.24 sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69D.25 tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70D.26 tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Standard C Time & Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71E.1 asctime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71E.2 clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71E.3 ctime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71E.4 difftime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72E.5 gmtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72E.6 localtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72E.7 mktime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72E.8 strftime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72E.9 time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Standard C Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75F.1 calloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75F.2 free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75F.3 malloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75F.4 realloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

Other standard C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77G.1 abort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77G.2 assert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77G.3 atexit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77G.4 bsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78G.5 exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78G.6 getenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78G.7 longjmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78G.8 qsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78G.9 raise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79G.10 rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79G.11 setjmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79G.12 signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79G.13 srand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80G.14 system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80G.15 va arg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

ASCII Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

Demarrage Unix & GNU/Linux

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 9

1 Procedure de Login

Suivant la salle ou vous vous trouvez (ici c’est la salle Stroustrup, en hommage au createur du langageC++), le type de distribution Linux installee sur la machine, de petites differences dans le mode deconnexion peuvent survenir.Pour se connecter a l’une des machines, il faut bien entendu, avoir un acces a celle-ci c-a-d avoir uncompte.La plupart du temps, pour se connecter, il suffit de donner son nom de login et son mot de passe aulogiciel de connexion (la plupart du temps xdm, gdm ou encore kdm). Vous obtenez une nouvelle fenetreressemblant a la figure 1.

Fig. 1 – Connexion a une machine en mode graphique (ici Ulysse avec gdm)

Login : saisissez ici votre identifiant ou login et enterPassword : saisissez ici votre mot de passe (Attention les lettres frappees s’affichent sous la formed’etoiles) et enter.Vous vous trouvez alors dans l’environnement LINUX, et vous avez une fenetre du type de la figure 2.

Fig. 2 – Connexion reussie vous pouvez travailler

Toute la puissance d’un OS multitaches multiutilisateurs est a vous. Mais saurez-vous en tirer partie ?

1.1 Remarque sur le mot de passe

X Vous seul connaissez le mot de passe.X Si vous l’oubliez, la seule solution est de contacter l’administrateur reseau pour l’effacement de l’ancien

mot de passe.X Le mot de passe est compose d’au moins 6 caracteres et au maximum 8 dont 2 au moins ne sont pas

des lettres.X Conseil : melanger les lettres, chiffres, majuscules et minuscules.

Yann MORERE Licence E.E.A. Universite de Metz

10 TPs de Langage C/C++

1.2 Pour changer de mot de passe

X yppasswd ou passwd et enterX La machine vous demande l’ancien mot de passe et enterX Elle vous demande le nouveau et enterX Puis elle redemande le nouveau pour confirmation et enterSi vous n’avez pas de message d’erreur, le mot de passe est alors change.

1.3 Terminer votre session

Pour terminer votre session LINUX (se deloger), il vous suffit de terminer la session graphique a l’aidedu menu approprie. Je ne donnerai aucun detail, car ceci est tres variant d’un gestionnaire de fenetre aun autre.

2 Forme et validation d’une commande

Une ligne de commande possede la forme generale suivante :

nom-de-commande [options] arguments

ou l’option a la forme -lettre.

Exemple : Dans la commandels -s -i toto titils est le nom de la commande, -s -i sont les options, toto et titi sont les

arguments. Plusieurs options peuvent etre regroupees derriere le signe -.ls -si toto titi

Une ligne de commande n’est recue et executee par le systeme qu’apres validation par enter.

3 Commande importante : man

La syntaxe est la suivante :man commande

ouman -k commande

Cette commande affiche la page de manuel correspondante a la commande. On y trouve tous les detailsconcernant son utilite, sa syntaxe et ses options.

Exemple : reponse du systeme a la commande man ls sur la machine OSF1 flore V4.0 1091 alpha

ls(1)

NAME

ls - Lists and generates statistics for files

SYNOPSIS

ls [-aAbcCdfFgilLmnopqrRstux1] [file...|directory...]

STANDARDS

Interfaces documented on this reference page conform to industry standardsas follows:

ls: XPG4, XPG4-UNIX

Refer to the standards(5) reference page for more information about indus-

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 11

try standards and associated tags.

Pour toutes questions au sujet de la commande man, taper :

man man

4 Les editeurs de texte

Un editeur de texte est un outil pour ecrire un fichier texte pur c’est a dire sans mise en forme (il necontient que des caracteres de la table ASCII) (edit sous DOS, turbo pour la programmation TurboPas-cal), alors qu’un traitement de texte est un outil pour ecrire et mettre en forme du texte (WordPerfect,MS Word).

4.1 vi

vi est un editeur video, c’est a dire pleine page et interactif. Il est possible d’inserer du texte a toutendroit dans le fichier en edition. (Cf. figure 3)L’appel de vi s’effectue de la maniere suivante :X viX vi fichierX vi +n fichier pour se placer directement a la n-ieme ligne du fichierX vi +/motif fichier pour se placer directement a la premiere occurrence du motif dans le fichier

Fig. 3 – Fenetre d’edition pleine page vi

Il dispose de 3 modes de travail :

Mode commande permet les deplacements, les recherches, les destructions, etc... C’est le mode pardefaut.

Mode execution permet l’utilisation de toutes les commandes de ed (editeur en ligne UNIX). Modeutilise pour les commandes globales et les commandes gerant les fichiers.

Mode saisie permet la saisie de texte.

4.1.1 Mode saisie

Pour passer en mode saisie (depuis le mode commande) il faut taper une des commandes d’edition :X a pour ”append” (ajout) ajoute du texte apres le curseur.X A pour ”append” (ajout) ajout du texte en fin de ligne.X i pour ”insert” (insertion) insere du texte devant le curseur.X I pour ”insert” (insertion) insere du texte en debut de ligne.X o pour ”open” (ouvrir) ouvre une ligne apres le curseur.X O pour ”open” (ouvrir) ouvre une ligne en fin de ligne.

Yann MORERE Licence E.E.A. Universite de Metz

12 TPs de Langage C/C++

4.1.2 Mode commande

Pour repasser en mode commande il faut appuyer sur ESC.

4.1.3 Deplacement du curseur

Deplacement du curseur en mode commande :X x,j,k et l deplacent le curseur dans les 4 directions (O, S, N et E). Ces touches peuvent etre remplacees

par les fleches du clavier.X w place le curseur au debut du mot suivantX b place le curseur au debut du mot precedentX e place le curseur a la fin du mot courantX O place le curseur en debut de ligneX $ place le curseur en fin de ligneX enter place le curseur au debut de la ligne suivanteX ^F avance le curseur d’une pageX ^B recule le curseur d’une pageX G place le curseur en fin de fichierX nG place le curseur a la n-ieme ligne du fichierX /motif / place le curseur a la prochaine occurrence du motifX mc definit une marque : elle associe la position du curseur au caractere c. On peut alors retourner d’un

autre endroit du fichier a cette position par la commande ‘c ou au debut de la ligne par ’c

4.1.4 Commandes d’effacement et remise de texte

X x efface le caractere sous le curseurX dw efface un motX db efface le mot precedentX D efface la fin de la ligneX dd efface la ligne du curseurX rc remplace le caractere courant par cX ~ remplace une minuscule par une majuscule et vice-versaX p reinsere le texte dernierement efface

4.1.5 Insertion d’un fichier exterieur

X :r fichier insere apres la ligne courante un fichier exterieur

4.1.6 Annulation de la derniere commande

X u annule la derniere commande effectuee

4.1.7 Recherche et remplacement

X :/motif place le curseur sur la prochaine occurrence de motifX :s/motif /chaıne/ remplace dans la ligne courante la premiere occurrence de motif par la chaıneX :s/motif /chaıne/g remplace dans la ligne courante toute occurrence de motif par la chaıneX :1,10s/motif /chaıne/g remplace toute occurrence de motif par la chaıne de la premiere a la dixieme

ligneX :.,$%s/motif /chaıne/g remplace toute occurrence de motif par la chaıne depuis la ligne courante

(designee par ".") jusqu’a la derniere ligne du fichier (designee par "$")X :%s/motif /chaıne/g remplace dans tout le fichier toute occurrence de motif par la chaıne

4.1.8 Deplacement de texte

X mc definit le debut de la section a deplacerX se deplacer a la fin de la section a deplacer et frapper d’c, la fraction de texte est alors supprimee et

placee dans le tamponX se deplacer a l’endroit voulu et frapper p qui insere le texte contenu dans le tampon.

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 13

4.1.9 Mode execution

Le mode execution est active depuis le mode commande par la caractere ’ :’ suivi de la commande :X :w nom fichier sauvegarde le fichier nom fichierX :w sauvegarde du fichierX :wq sauvegarde et quitte viX :q ! quitte vi sans sauvegardeX :x equivalent a :wq

4.2 emacs

Les principaux avantages d’emacs sont l’extensibilite, la personnalisation et l’auto-documentation. Ilpossede de nombreuses fonctionnalites autres que celles de l’edition.On peut compiler un programme, lire du courrier electronique, lire les forums, recuperer un fichier parftp... emacs signifie editor macros.L’appel d’emacs s’effectue de la maniere suivante :X emacsX emacs fichierX emacs +n fichier pour se placer directement a la n-ieme ligne du fichier

Fig. 4 – Fenetre d’edition emacs

La plupart des commandes emacs font intervenir :X la touche <CTRL> frappee en meme temps qu’un autre caractere. Elle est habituellement notee C-. Par

exemple C-p designe la touche <CTRL> frappee en meme temps que p.X la touche META, existante sur la clavier, soit la touche <ALT> ou encore la touche <ESC> (dans ce cas

elle doit etre relachee avant la touche qui suit). Elle est notee M-.

4.2.1 Les modes d’edition d’emacs

Selon que l’on travaille sur un fichier texte, un programme C, un fichier de donnees, les besoins d’editionsont differents. emacs propose donc plusieurs modes d’edition qui definissent un environnement de travailadapte au type de fichier.Modes principaux :X le mode FundamentalX le mode TextX le mode LispX le mode CIl existe des modes secondaires utilises en conjonction avec un mode principal :X le mode Fill : les lignes sont automatiquement coupees quand elles depassent la marge droite.

Yann MORERE Licence E.E.A. Universite de Metz

14 TPs de Langage C/C++

X le mode Abbrev : l’expansion des abreviations est impossible.X le mode Ovwrt : mode recouvrement.X le mode Narrow : rend accessible qu’une partie du buffer.

4.2.2 Notion de buffer

C’est une partie de la memoire d’emacs. A chaque ouverture de fichier un buffer portant le meme nomest cree. Les modifications n’affectent pas tout de suite le fichier sur disque mais le buffer. Il faut sauverle fichier pour que les modifications soient effectuees sur le fichier d’origine.

4.2.3 Commande de deplacement du curseur

X C-p place le curseur sur la ligne precedenteX C-n place le curseur sur la ligne suivanteX C-f avance le curseur d’un caractereX M-f avance le curseur a la fin du mot courant ou suivantX C-b recule le curseur d’un caractereX M-b recule le curseur au debut du mot courant ou du precedentX C-a place le curseur en debut de ligneX C-e place le curseur en fin de ligneX M-< place le curseur en debut de fichierX M-> place le curseur en fin de fichierX C-v avance la fenetre d’un ecranX M-v recule la fenetre d’un ecranToutes ces commandes peuvent etre envoyees avec un argument numerique n. L’argument numerique estintroduit par C-u.La commande C-u 8 C-n avance le curseur de 8 lignes.

4.2.4 Insertion et suppression de texte

X C-d efface le caractere sur lequel se trouve le curseurX C-k efface la fin de la ligneX C-y reinsere le texte effaceX C-x u annule l’effet de la derniere modification

4.2.5 Edition simultanee de plusieurs fichiers

X C-x C-f fichier cree un nouveau tampon et y place le fichierX C-x C-b ouvre un nouveau tampon et une nouvelle fenetre sur l’ecran et y affiche la liste de tous les

tampons ouverts (cette fenetre peut etre supprimee avec C-x 1)X C-x b tampon place la curseur dans le tamponX C-x C-v fichier place le fichier dans le tampon courant, son contenu actuel est elimine.X C-x k tampon supprime le tampon (par defaut c’est le tampon courant qui est supprime)

4.2.6 Recherche et remplacement

X C-s mot recherche la premiere occurrence du mot dans la suite du texte. A chaque fois que l’utilisateurfrappe une nouvelle lettre du mot, le curseur se place sur la prochaine occurrence de ce qui a ete frappe.La repetition de C-s recherche l’occurrence du mot suivant.

X C-r mot a le meme effet que C-s, mais la recherche se fait sur le texte qui precede.X M-% chaıne nouvelle chaıne remplace une chaıne de caracteres par une nouvelle chaıne. L’utilisateur

doit valider chaque remplacement. S’il frappe ! les validations sont omises

4.2.7 Insertion d’un fichier

X C-x i fichier insere le fichier a l’endroit du curseurPour n’inserer qu’une partie du fichier effectuer les commandes suivantes :X C-x C-f fichier insere le fichier dans un nouveau tamponX Placer le curseur au debut de la region a insererX C-@ ou C-ESPACE marque le debut de la region

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 15

X Placer le curseur a la fin de la region a insererX C-w efface la region delimiteeX C-x b revient au tampon initialX Se placer a l’endroit voulu de l’insertionX C-y insere le contenu du tampon auxiliaire

4.2.8 Suppression de fenetres

X C-x 1 supprime toutes les fenetres qui ont ete ouvertes a l’exception de celle ou se trouve le curseur

4.2.9 Sauvegarder et quitter emacs

X C-x C-s sauvegarde les modifications effectuees si emacs connaıt le nom de fichier. Sinon l’utilisateurest invite a entrer un nom de fichier dans le mini tampon.

X C-z quitte emacs provisoirement (le processus est suspendu). Le retour a emacs se fait en frappant fgou encore %emacs.

X C-x C-c quitte emacs definitivement.

4.3 nedit, gedit, gnotepad & kedit

nedit, gedit, gnotepad & kedit sont des editeurs graphiques qui ressemblent beaucoup aux editeursrencontres sous les environnements PC, Mac, Amiga (Linux, Windows 3.xx et 9x, DOS, Mac OS, AmigaOS). nedit, gedit, gnotepad & kedit peuvent etre completement geres a la souris et possedent desmenus conviviaux pour l’edition, la recherche de texte, le copier coller, la selection de texte.nedit utilise la bibliotheque graphique Motif, alors que gedit, gnotepad utilisent les bibliotheques del’environnement gnome (GLIB, GTK+) et kedit, lui est base sur KDE et les bibliotheques QT.

Fig. 5 – Fenetre de l’editeur graphique nedit

Yann MORERE Licence E.E.A. Universite de Metz

16 TPs de Langage C/C++

Fig. 6 – Fenetre de l’editeur graphique gnp

Fig. 7 – Fenetre de l’editeur graphique gedit

Fig. 8 – Fenetre de l’editeur graphique kedit

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 17

Il possede aussi des predispositions pour la programmation. Il gere l’auto-indentation des lignes deprogrammes, la gestion du nombre des parentheses, l’affichage des mots-cles du langage.

5 Compiler et Automatiser les taches : make

5.1 Que fait make

Sur les systemes de la famille Unix, make remplit le meme role que les gestionnaires de projets quel’on retrouve dans la plupart des environnements de developpement integres (IDE) soit sous windowsou encore MacOS. Quel que soit son nom et sa forme, son objectif est toujours le meme : centraliserl’ensemble des fichiers et ressources dont se compose un projet, gerer les dependances et assurer unecompilation correcte.Ainsi si l’on modifie l’un des fichiers sources, le gestionnaire de projet en tiendra compte et saura qu’ilfaut recompiler ce fichier et proceder de nouveau a une edition de liens pour obtenir un executable ajour.De plus make constitue un puissant langage de programmation, specialise dans la gestion des projets.

5.2 Dans le vif du sujet

Partons d’un exemple : helloworld. Mais dans notre cas il sera decompose sur 2 fichiers sources et unfichier d’entete.Fichier main.c

#include <stdio.h>#include "helloworld.h"int main(int argc, char *argv[]){

hello();exit(0);

}

Fichier helloworld.h

void hello();

Fichier helloworld.c

#include <stdio.h> void hello() {printf("bonjour le monde\n");

}

Afin de compiler ce programme il est possible de le faire de trois manieres differentes :

1. gcc helloworld.c main.c -o helloworld

2. gcc -c helloworld.cgcc -c main.cgcc main.o helloworld.o -o helloworld

3. ou avec make

La solution 1 convient bien s’il s’agit d’un petit exemple. Mais s’il est question d’un projet plus importantil devient necessaire d’ecrire un script de compilation. Dans ce cas la solution 3, utilisant make est la pluselegante, car le programme utilise un fichier Makefile qui gere les dependances entre les fichiers.Nous allons donc ecrire le fichier Makefile, il ressemble a ceci :

helloworld: main.o helloworld.ogcc -o helloworld main.o helloworld.o

main.o: main.cgcc -c main.c

helloworld.o: helloworld.cgcc -c helloworld.c

Yann MORERE Licence E.E.A. Universite de Metz

18 TPs de Langage C/C++

Un Makefile contient ainsi un ensemble de regles, dont chacune est constituee d’une ”cible”, de ”de-pendances” et de commandes. Il est important de de realiser l’indentation des lignes ci-dessus avec destabulations et non des espaces. Ceci occasionnerait des erreurs lors du makeLa premiere regle definit la cible helloworld ce qui signifie que son role reside dans la production d’unfichier helloworld. Cette regle possede 2 dependances main.o et helloworld.o. Cela indique que pourelaborer le programme helloworld, il faut prealablement disposer de ces 2 fichiers. Il vient ensuite lacommande shell qui permet de generer helloworld a partir des dependances. Cette commande consistea appeler la compilation pour obtenir l’executable helloworld a partir des deux fichiers objets.La regle suivante est encore plus simple, elle donne le moyen de creer le fichier objet main.o. La syntaxed’un Makefile se revele donc assez simple. On peut alors l’utiliser en vue de la recompilation de notreprogramme simplement e, lancant la commande make helloworld ou encore plus simplement make, carl’outil prend par defaut la premiere cible trouvee.Que va t’il se passer ? Make cherchera a generer helloworld : pour cela il verifiera d’abord si les fi-chiers requis sont disponibles. S’il manque par exemple main.o, il appliquera alors la regle pour produirece fichier et ainsi de suite si main.o necessitait d’autres dependances. Une fois toutes les dependancessatisfaites, la commande pour produire helloworld sera executee afin d’obtenir notre fichier executable.

5.3 Pourquoi passer par make

En fait, le principal interet de cet outil reside dans le fait qu’il n’effectue que le strict minimum. Ainsicomme vous l’avez fait precedemment, si seul le fichier helloworld.c est modifie, lors de la recompilationdu projet, make constatera que la date de modification de helloworld.c est plus recente que la creationdu fichier helloworld.o, donc il le recompilera, par contre dans le cas de main.c tout est correct, et iln’a pas besoin de regenerer la fichier objet.On gagne ainsi un temps considerable lors de la compilation de gros projet, en ne recompilant que ce quiest necessaire.

5.4 Plus loin avec GNU Make

Bien sur si make apporte un aide non negligeable poue la compilation de projet, ecrire un Makefilecomplet devient tres vite agacant des que le projet devient important. Heureusement pour nous, toutceci peut etre automatise.GNU make propose des mecanismes grace auxquels il peut deduire pratiquement tout seul les regles aappliquer. Comme il s’agit d’un langage, make gere les variables dont certaines possedent une significationparticuliere. Il est important d’en connaıtre au moins 8 :– CC definit le compilateur C par defaut,– CFLAGS definit les options a lui transmettre,– CXX et CXXFLAGS jouent le meme role pour le compilateur C++,– LIBS definit les librairies a utiliser pour la compilation,– DESTDIR definit le chemin sur lequel le programme se verra installe un fois compile,– @ et < representent respectivement la cible et la dependance courante.De plus GNU Make possede des regles predefinies : ainsi il sait que par defaut il doit produire un fichiertoto.o a partir d’un fichier toto.c en invoquant le compilateur defini par la variable CC, avec les optionsCFLAGS. Ainsi il est possible de simplifier le Makefile comme suit :

CC = gcc OBJS = main.o helloworld.o helloworld : $(OBJS)$(CC) -o $(@) $(OBJS)

On donne a CC la valeur gcc et l’on garde egalement les dependances dans la variable OBJS afin d’eviterde les entrer manuellement. La seule regle que nous avons, indique comment produire helloworld apartir des dependances definie par la variable OBJS. On utilise alors le compilateur indique par CC. Onremarque aussi l’emploi de la variable @ qui, a tout instant, represente la cible de la regle ou elle figure ;dans le cas present sa valeur est donc helloworld. Il ne s’avere plus necessaire d’indiquer les regles pourproduire main.o et helloworld.o.

5.5 Nouvelles regles predefinies

Si les regles prevues dans GNU make ne vous suffisent pas, il est possible d’en redefinir des nouvelles. Ilest alors possible de creer un fichier postscript a partir d’un fichier dvi par exemple lors de la redactionde document sous LATEX2ε.

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 19

%.ps: %.dvidvips -ta4 -o $(@) $(<)

On exprime ici le faite, que l’on cree un fichier postscript a partir d’un fichier portant le meme nomavec le suffixe .dvi en utilisant la commande dvips.

5.6 make all, installation et nettoyage

Afin de simplifier la compilation des programmes, la regle all est tres interessante. Celle-ci lancera lacompilation complete de notre programme.

all: helloworld

Ce permet de plus d’avoir un terme generique pour lancer la compilation complete de n’importe quelprojet.La seconde chose importante est l’installation du programme. Cette nouvelle regle est dependante dela compilation complete (all). Grace a la commande make install, il sera possible de copier l’execu-table dans le sous-repertoire bin de DESTDIR ainsi que ses diverses ressources dans DESTDIR/share, ladocumentation dans DESTDIR/doc et la page de manuel dans DESTDIR/man.

install: allcp helloworld $(DESTDIR)/binmkdir -p $(DESTDIR)/doc/helloworldcp manual.ps $(DESTDIR)/doc/helloworldcp README $(DESTDIR)/doc/helloworldcp helloworld.1 $(DESTDIR)/man/man1

Une fois l’installation faite, il ne reste plus qu’a faire le menage des fichiers temporaires crees lors de lacompilation et qui ne servent plus. La regle clean detruira ces fichiers. Il suffira de taper make cleanpour obtenir une arborescence propre.

clean:rm -f *.o *~

Bien sur cette regle de depend d’aucune autre.Le fichier makefile precedent est complete afin de pouvoir compiler, installer (dans le repertoire bin quevous aurez cree dans votre repertoire) et nettoyer le projet helloworld.

CC= gccCFLAGS = -O2DESTDIR = $(HOME)OBJS = main.o helloworld.ohelloworld : $(OBJS)

$(CC) -o $(@) $(OBJ)all: helloworld install: all

cp helloworld $(DESTDIR)/binmkdir -p $(DESTDIR)/doc/helloworldcp README $(DESTDIR)/doc/helloworld

clean:rm -f *.o *~

5.7 Compiler du C++

Reprenons l’exemple : helloworld. Mais on modifiera son contenu pour le rendre compilable en C++.Fichier main.cpp ou main.C

#include <iostream.h>int main(int argc, char *argv[]){

cout << "hello world\n";exit(0);

}

Yann MORERE Licence E.E.A. Universite de Metz

20 TPs de Langage C/C++

Afin de compiler ce programme par le compilateur C++ :

1. g++ main.cpp -o helloworld

2. ou g++ main.C -o helloworld

Licence E.E.A. Universite de Metz 4 mars 2004

Sujets de TPs

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 23

Licence E.E.A.TP N 1 de Langage C

6 Polynome du second degres

Le but du tp est d’ecrire un programme que permet de trouver les solutions d’un polynomes du seconddegres de la forme a x2 + b x + c = 0. Pour des questions de facilite on entrera les valeurs de a, b et cdirectement dans des variables de type �entier�.

1. Ecrire l’algorithme qui permettra de resoudre notre probleme. Il ne faudra oublier aucun cas (tousles types de solutions sont demandes).

2. Un menu devra permettre a l’utilisateur de choisir de quitter le programme ou de resoudre un autrepolynome.

3. Les solutions seront presentees convenablement et le programme devra comporter les points sui-vants :V Ecriture a l’ecran du polynome sous le forme a x2 + b x + c = 0V Informations a l’utilisateur des calculs intermediaires necessairesV Presentation soignee des solutions calculeesV Enfin menu de demande d’abandon ou de poursuite du programme

7 Changement de Base

Le but du TP est d’ecrire un programme qui permet de representer un nombre sous differentes bases.

Rappel : Un nombre A s’ecrit en base B, (B > 1) de maniere unique sous la forme :

A = anBn + an−1Bn−1 + . . . + aiB

i + . . . a1B1 + a0B

0 =n∑

i=0

aiBi avec∀i ∈ [0, n], ai ≤ B − 1

Plutot que d’ecrire un nombre A dans la base B sous la forme precedente, on choisit la notation : A =(an an−1 . . . ai . . . a1 a0)B Pour les bases de 2 a 10 on conserve les chiffres arabes habituels (1, 2, . . . , 10).Mais si on travaille avec des bases superieures a 10, on ajoute generalement les lettres de l’alphabets(A,B,C,D, . . .)

Exemple : (4092)10 = (14634)7 = (FFC)16 = (111111111100)2

Travail demande

1. Ecrire un programme modulaire comportant un menu qui autorise l’acces aux traitements decritsdans les points suivants

2. Le menu doit permettre d’acceder aux modules de base suivants :– un module ”change_10_vers_B”qui convertit un nombre entier en base 10 choisi par l’utilisateur

vers une base B, (1 < B < 11)– un module ”change_B_vers_10” qui convertit un nombre entier ecrit dans la base B, (1 < B <

11) choisi par l’utilisateur vers la base 10– un module ”change_B1_vers_B2” qui convertit un nombre entier ecrit dans la base B1, (1 <

B1 < 11) choisi par l’utilisateur vers la base B2, (1 < B2 < 11)

3. Modifier les algorithmes afin de traiter les cas ou la base B, (1 < B < 33)

8 Les nombres complexes

Le but du TP est d’ecrire un programme que permet de manipuler un nombre complexe. Un nombrecomplexe s’ecrit sous la forme A + i B. A est la partie reelle et B la partie imaginaire.

Yann MORERE Licence E.E.A. Universite de Metz

24 TPs de Langage C/C++

1. Ecrire un algorithme modulaire comportant un menu qui autorise l’acces aux traitements decritsdans les questions suivantes.

2. Le menu doit permettre d’acceder aux modules de base suivants :V un module ”LireComplexe” qui saisit un nombre complexe choisi par l’utilisateur.V un module ”EcrireComplexe” qui affiche le nombre complexe sous la forme A + iB.V un module ”NormeComplexe”qui calcule la norme du nombre complexe.V un module ”Argument” qui calcul l’argument d’un nombre complexe.V un module ”Cart2Pol”qui convertit les coordonnees cartesiennes en coordonnees polaires.V un module ”SommeComplexe” qui additionne 2 nombres complexes.

3. Ces trois derniers modules sont optionnels (pour les rapides ...) :V un module ”SoustractionComplexe” qui soustrait 2 nombres complexes.V un module ”ProduitComplexe” qui multiplie 2 nombres complexes.V un module ”DiviseComplexe” qui divise 2 nombres complexes.

Dans la preparation, on s’attachera a presenter les formules mathematiques qui seront utilisees dans lesdifferents algorithmes.

bTous a vos gommes et crayons de papier

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 25

Licence E.E.A.TP N 2 de Langage C

9 Les tableaux

Le but du TP est de realiser la gestion d’un reseau routier par l’intermediaire de tableaux. On desirerelier N villes par un reseau de routes qui permet de relier n’importe quelles villes entre elles. On connaıtaussi les distances qui separent les villes entre elles.

Calais

Dunkerque

Lille

Douai Valenciennes

Pas-de-Calais

Nord

37 Km

92 Km

67 Km

30 Km

107 Km 45 Km

83 Km

135 Km

28 Km

110 Km

Fig. 9 – Schema du reseau routier

On definira Villes un tableau de chaıne de caracteres qui contiendra toutes les villes de notre reseau.On definira ensuite un tableau a deux dimensions Distances[ville1,ville2] qui contiendra les distancesentre deux villes du tableau Villes. On supposera que les distances sont toutes distinctes entre elles etont des valeurs entieres.

1. Ecrire une procedure d’initialisation des tableaux Villes et Distances.

2. Ecrire une fonction distance(ville1, ville2) qui renvoie la distance entre deux villes du tableaux.

3. Ecrire une procedure qui trouve les deux villes les plus proches et affiche leurs noms.

10 Traitement de chaınes

Le but du TP est d’ecrire un programme C qui realise la saisie d’une chaıne de caracteres ainsi que sontraitement. Les differentes procedures ou fonctions a creer sont les suivantes :

1. Le calcul du nombre de caracteres alphanumeriques de la chaıne

2. Calcul de l’occurrence d’un caractere choisi par l’utilisateur

3. Remplacement d’un caractere par un autre dans toute la chaıne

Pour la bonne marche du programme il est demande de creer un menu qui permet d’acceder a toutes lesfonctionnalites decrites precedemment.par exemple :

1. Calculer le nombre de caracteres alphanumeriques

2. Calculer l’occurrence d’un caractere

3. Remplacer un caractere

Donner votre choix :

Yann MORERE Licence E.E.A. Universite de Metz

26 TPs de Langage C/C++

11 Le Verlan

Exemple : Toutes les syllabes d’un mot seront separees lors de la lecture par un /.Entrez la phrase : Bon/jour, je par/le le Ver/lan.La traduction donne : jourbon, je lepar le lanver.

– Ecrire un module lisant une phrase se terminant obligatoirement par un point.– Ecrire un module effectuant la traduction.– Ecrire un module de traduction donnant le resultat suivant :

Entrez la phrase : Bonjour, je parle le Verlan.La traduction donne : ruojnob, ej elrap el nalrev.

12 Les palindromes

Rappel : Un palindrome est un mot ou une phrase pouvant se lire indifferemment a l’endroit ou al’envers. Generalement les signes de ponctuations tels que les espaces, les virgules, les points... ne sontpas pris en consideration (afin de simplifier le probleme on ecartera aussi le cas des accentuations).

Exemple : Tu l’as trop ecrase, Cesar ce port-salut.

Travail demande :

1. Ecrire un programme modulaire comportant un menu qui autorise l’acces aux traitements decritsdans les points suivants

2. Ecrire un module lisant une phrase se terminant obligatoirement par un point (Le programmeredemandera la saisie de la phrase si celle rentree n’est pas terminee par un point)

3. Ecrire un module transformant les majuscules en minuscules dans une phrase

4. Ecrire un module supprimant tous les signes de ponctuations et espaces d’une phrase

5. Ecrire un module verifiant que la phrase entree est bien un palindrome

6. Modifier le module precedent de maniere a donner la position de la premiere difference dans le casou la phrase n’est pas un palindrome

bTous a vos gommes et crayons de papier

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 27

Licence E.E.A.TP N 3 de Langage C

13 Resolution d’une equation f(x) = 0

Le but du TP est de trouver les racines d’une fonction quelconque donnee. Pour cela nous allons utiliserdiverse methodes numeriques.Pour simplifier le probleme nous allons nous placer dans un cas precis, l’etude de la racine de la fonctionf(x) = sin(x) − x cos(x) qui se trouve dans l’intervalle [3, 2; 4, 6].

0 2 4 6 8 10 12 14 16 18 20 -20

-15

-10

-5

0

5

10

15

20

Fig. 10 – Representation Graphique de la fonction f(x) = sin(x) − x cos(x)

Comme les methodes presentees sont toutes iteratives et numeriques il est essentiel de definir quel degresde precision nous voulons pour le resultat. Dans notre cas nous le choisirons egal a 10−6.Voici quelques conseil pour mener a bien votre TP :

1. Definir une fonction qui calcule les valeurs de la fonction etudiee.Exemple :

double f(double x) {return sin(x)-x*cos(x);

}

2. Definir une fonction qui calcule les valeurs de la derivee de la fonction etudiee.Exemple :

double df(double x) {return x*sin(x);

}

3. Definir une fonction qui nous informe que la precision est atteinte.Nous allons donc etudier trois methodes numeriques pour resoudre notre probleme.

13.1 Dichotomie

L’algorithme est le suivant :1. On se place sur un segment note [u , v] tel que f(u) . f(v) < 0, la continuite de f implique l’existence

d’une racine ente u et v

2. En posant w = (u + v) / 2, on calcule f(w). Si l’on trouve zero, w est une racine de f . Sinon onrecommence en se placant sur celui des deux segments [u , w] ou [w , v] qui verifient une conditionde la forme f(x) . f(y) < 0

Yann MORERE Licence E.E.A. Universite de Metz

28 TPs de Langage C/C++

y x u=0

v=1

2 3

4 5

Fig. 11 – Resolution par Dichotomie

13.2 Interpolation Lineaire

Cette methode est aussi appelee la methode de la secante. Elle est basee sur le principe suivant :

1. Partant des points u et v, on considere la secante passant par les points (u , f(u)) et (v , f(v)),qui coupe l’axe des x en un point d’abscisse w. Cette technique de remplacement d’une courbepar une droite est aussi appelee Interpolation Lineaire. Pour qu’il y aie une racine il faut, commeprecedemment que f(u) . f(v) < 0. w est donne par :

w =−

(−

(f(v)− f(u)

v−u

). v + f(v)

)

f(v)− f(u)v−u

2. On choisit alors de remplacer u ou v par w et l’on recommence jusqu’a trouver f(w) inferieur anotre precision. On notera que si l’on choisit de remplacer u par w alors v reste constant.

y

x u=0

v=1

2 3

Fig. 12 – Resolution par Interpolation Lineaire

13.3 Newton

Il s’agit d’une methode proche de celle de la secante, ou ici la corde definie par les deux extremites del’intervalle u et v est remplacee par la tangente au point u.

1. La tangente en (u , f(u)) a la courbe de f coupe l’axe des x en un point d’abscisse v = u − f(u)f ′(u)

2. on remplace alors u par v et l’on recommence jusqu’a obtenir une valeur negligeable pour f(v)

3. on pourra prendre pour point de depart de u = (u + v) / 2

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 29

y x u=0

v=1

2 3

Fig. 13 – Resolution par La methode de Newton

13.4 Travail demande

1. Ecrire un algorithme modulaire comportant un menu qui autorisera l’acces aux differentes methodesde calcul

2. Les trois methodes de calcul seront decrites dans trois fonctions separees

3. Donner les differentes solutions trouvees par les differentes methodes de calcul. Les comparer.

4. Repeter les calculs pour les intervalles [7; 9]et [10; 12]

5. Question subsidiaire : Faites un essai avec l’intervalle [2; 5], les resultats sont ils differents ? Pour-quoi ?

14 Calcul integrale

Le but du TP est d’ecrire un programme C qui calcul l’integrale numerique d’une fonction y = f(x)sur un intervalle donne par l’utilisateur. Pour cela nous allons utiliser plusieurs methodes d’integrationsnumeriques.

14.1 La methode des rectangles

Y

X n intervalles

a b

pas de calcul

y=f(x)

L’integrale peut s’ecrire :

I =b− a

n

n−1∑

k=0

f

(a + k × b − a

n

)

Fig. 14 – Representation de la methode des rectangles

14.2 La methode du point median

La methode du point median est identique a la methode des rectangles mais a correspond au milieu dupas de calcul et plus a l’une des aretes du rectangle.

Yann MORERE Licence E.E.A. Universite de Metz

30 TPs de Langage C/C++

14.3 La methode des trapezesY

X n intervalles

a b

pas de calcul

y=f(x)

L’integrale peut s’ecrire :

I =b− a

n

(12f(a) +

n−1∑

k=1

f

(a + k × b− a

n

)+

12f(b)

)

Fig. 15 – Representation de la methode des trapezes

14.4 La methode de Simpson

Y

X n intervalles

a b

pas de calcul

y=f(x)

L’integrale peut s’ecrire :

I =b− a

3n

(f(a) + 4× f

(a +

b− a

n

)+ 2× f

(a + 2× b− a

n

)+ 4× f

(a + 3× b− a

n

)+ · · ·+ f(b)

)

Fig. 16 – Representation de la methode de Simpson

14.5 Travail demande

On fera attention au choix du pas de calcul, et on determinera sont effet sur la precision et les temps decalcul.◦ Ecrire un module qui calcul le resultat de f(x)◦ Ecrire un module qui determine si un nombre est pair ou impair◦ Ecrire les modules qui calculent l’integrale d’un fonction sur un intervalle donne par les differentes

methodes citees. Il pourra etre interessant de creer un module par methode.◦ Ecrire un module qui permet l’affichage d’un menu donnant les choix suivants :

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 31

1. Bornes de l’integrale

2. Pas de calcul de l’integrale

3. Integrale par la methode des rectangles

4. Integrale par la methode du point median

5. Integrale par la methode des trapezes

6. Integrale par la methode de Simpson

7. Quitter le programmeDonner votre choix :

bTous a vos gommes et crayons de papier

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

Annexes Utiles

Cette page est laissee blanche intentionnellement

Memento des commandes du shell

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 37

Memento des commandes du shell

A.1 Diffusion du present document

Ce document appartient a IDEALX. Il est librement diffusable dans les termes de la Licence de Docu-mentation Libre GNU (traduit de la GNU Free Documentation License).

A.2 Gestion des utilisateurs

Syntaxe Mnemonique Significationuseradd Ajoute un utilisateur (option -m : cree le re-

pertoire personnel avec)userdel Supprime un utilisateur, son repertoire per-

sonnel et sa boıte aux lettresgroupadd Ajoute un groupegroupdel Supprime un groupegroupmod Modifie un groupepasswd <utilisateur> Password Changer le mot de passe de <utilisateur>chfn <utilisateur> Change Full Name Change le nom complet de <utilisateur>chsh <utilisateur> Change Shell Change le shell de <utilisateur>su Super User Devient un autre utilisateurid Donne les droits du shellwho Qui est connecte ?last Qui s’est connecte recemment ?

Yann MORERE Licence E.E.A. Universite de Metz

38 TPs de Langage C/C++

A.3 Gestion des fichiers

Syntaxe Mnemonique Significationcd <repertoire> Change Directory Place le shell dans le repertoire <repertoire>

(l’invite change en consequence). Si <reper-toire> est omis, retourne dans le repertoirepersonnel ( ).

ls <repertoire> List Liste les fichiers du <repertoire>.ls -l <repertoire> Liste le repertoire en format long (droits

UNIX, date de derniere modification).locate <motif> Localiser Liste les fichiers dont le nom contient

le <motif>, qui peut contenir des jokers (*et ?) .

mv <source> <dest> Move Deplace <source> vers <dest>. Si <dest> estun repertoire, <source> est deplace dedanssans changer de nom.

cp <source> <dest> Copy Meme sens des arguments que mv, mais faitune copie et non un deplacement.

ln -s <source> <dest> Link Cree un lien symbolique de <source> vers<dest>. Attention : si <dest> est un reper-toire relatif, il s’interprete a partir du reper-toire dans lequel se trouve <source>.

rm <fichiers> Remove Efface les fichiers seulement. rm -r : efface desarborescences entieres.

mkdir <repertoire> Make Directory Cree un repertoirermdir <repertoire> Remove Directory Efface un repertoire (qui doit etre vide).chmod Change Mode Change les droits (rwxrwxrwx) d’un fichier ou

repertoire.chown Change Owner Change le proprietaire d’un fichier ou reper-

toire.chgrp Change Group Change le groupe a qui appartient un fichier

ou repertoire.

A.4 Recherche et archivage de fichiers

Syntaxe Mnemonique Significationfind Selectionne des fichiers dans une arborescence

selon divers criteres.xargs Execute une meme commande sur des noms

de fichiers fournis sur l’entree standard.cpio Copy In and Out Archiveur prenant les noms de fichiers sur son

entree standard (mode de compatibilite tarpossible).

tar Autre archiveur.gzip Logiciel de compression rapide et efficace.bzip2 Logiciel de compression tres lent mais tres ef-

ficace.du Disk Usage Place disque qu’occupe une arborescence.df Disk Free Place disque disponible sur toutes les parti-

tions.fuser Find User Qui a tel fichier ouvert en ce moment ?lsof List Open Files Quels fichiers tel processus a d’ouverts en ce

moment ?

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 39

A.5 Gestion des processus

Syntaxe Mnemonique Significationps Processes Affiche la table des processus (options ty-

piques : -ax).kill -<sig> <pid> Envoie un signal <sig> (pas necessairement

mortel) au processus numero <pid>.killall -<sig> <nom> Idem mais envoie le signal au(x) processus

dont le nom est <nom>.top Top ten Affiche les processus occupant le plus de res-

sources.nice Lance un processus en priorite reduite.renice Modifie la priorite d’un processus deja lance.ulimit Restreint les maxima de ressources des proces-

sus.nohup Protege une commande contre la fermeture de

son terminal.

A.6 Traitement de chaınes de caracteres (pour programmation shell)

Syntaxe Mnemonique Significationbasename Selectionne le dernier composant d’un chemin

d’acces.dirname Selectionne le repertoire parent d’un chemin

d’acces (dernier composant exclu).pwd Print Working Directory Renvoie le repertoire

courant.expr Substitution ou reconnaissance de motifs.

A.7 Flux de texte

Syntaxe Mnemonique Significationgrep <expr> Recherche le motif <expr>.head Affiche le debut du texte.tail Affiche la fin du texte.cut Selectionne par colonnes dans le texte.sed Stream Editor Recherche-remplacement dans le texte.yes Dit toujours la meme chose.wc Word Count Compte les mots.sort Trie les lignes du texte.md5sum Somme de controle cryptographique.

A.8 Autres outils de traitement du texte

Syntaxe Mnemonique Significationdiff Calcule les differences entre deux fichiers (ou

entre un flux et un fichier).patch Rustine Modifie un fichier texte d’apres les indications

de la sortie de la commande diff.

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

Librairies standards C

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 43

Standard C Input/Output

Sources : http://www.cppreference.com/

clearerr() clears errorsfclose() close a filefeof() true if at the end-of-fileferror() checks for a file errorfflush() writes the contents of the output bufferfgetc() get a character from a streamfgetpos() get the file position indicatorfgets() get a string of characters from a streamfopen() open a filefprintf() print formatted output to a filefputc() write a character to a filefputs() write a string to a filefread() read from a filefreopen() open an existing stream with a different namefscanf() read formatted input from a filefseek() move to a specific location in a filefsetpos() move to a specific location in a fileftell() returns the current file position indicatorfwrite() write to a filegetc() read a character from a filegetchar() read a character from STDINgets() read a string from STDINperror() displays a string version of the current error to STDERRprintf() write formatted output to STDOUTputc() write a character to a streamputchar() write a character to STDOUTputs() write a string to STDOUTremove() erase a filerename() rename a filerewind() move the file position indicator to the beginning of a filescanf() read formatted input from STDINsetbuf() set the buffer for a specific streamsetvbuf() set the buffer and size for a specific streamsprintf() write formatted output to a buffersscanf() read formatted input from a buffertmpfile() return a pointer to a temporary filetmpnam() return a unique filenameungetc() puts a character back into a streamvprintf, vfprintf, vsprintf write formatted output with variable argument lists

B.1 clearerr

Syntax :

#include <stdio.h>void clearerr( FILE *stream );

The clearerr function resets the error flags and EOF indicator for the given stream. When an error occurs,you can use perror() to figure out which error actually occurred.Related topics : feof(), ferror(), and perror().

Yann MORERE Licence E.E.A. Universite de Metz

44 TPs de Langage C/C++

B.2 fclose

Syntax :

#include <stdio.h>int fclose( FILE *stream );

The function fclose() closes the given file stream, deallocating any buffers associated with that stream.fclose() returns 0 upon success, and EOF otherwise.Related topics : fopen(), freopen(), and fflush().

B.3 feof

Syntax :

#include <stdio.h>int feof( FILE *stream );

The function feof() returns a nonzero value if the end of the given file stream has been reached.Related topics : clearerr(), ferror(), perror(), putc(), and getc().

B.4 ferror

Syntax :

#include <stdio.h>int ferror( FILE *stream );

The ferror() function looks for errors with stream, returning zero if no errors have occured, and non-zeroif there is an error. In case of an error, use perror() to determine which error has occured.Related topics : clearerr(), feof(), perror(),

B.5 fflush

Syntax :

#include <stdio.h>int fflush( FILE *stream );

If the given file stream is an output stream, then fflush() causes the output buffer to be written to thefile. If the given stream is of the input type, then fflush() causes the input buffer to be cleared. fflush()is useful when debugging, if a program segfaults before it has a chance to write output to the screen.Calling fflush( STDOUT ) directly after debugging output will ensure that your output is displayed atthe correct time.

printf( "Before first call\n" );fflush( STDOUT );shady_function();printf( "Before second call\n" );fflush( STDOUT );dangerous_dereference();

Related topics : fclose(), fopen(), fread(), fwrite(), getc(), and putc().

B.6 fgetc

Syntax :

#include <stdio.h>int fgetc( FILE *stream );

The fgetc() function returns the next character from stream, or EOF if the end of file is reached or ifthere is an error.Related topics : fputc(), getc(), putc(), and fopen().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 45

B.7 fgetpos

Syntax :

#include <stdio.h>int fgetpos( FILE *stream, fpos_t *position );

The fgetpos() function stores the file position indicator of the given file stream in the given positionvariable. The position variable is of type fpos t (which is defined in stdio.h) and is an object that canhold every possible position in a FILE. fgetpos() returns zero upon success, and a non-zero value uponfailure.Related topics : fsetpos(), fseek(), and ftell().

B.8 fgets

Syntax :

#include <stdio.h>char *fgets( char *str, int num, FILE *stream );

The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str.fgets() will stop when it reaches the end of a line, in which case str will be terminated with a newline. Iffgets() reaches num - 1 characters or encounters the EOF, str will be null-terminated. fgets() returns stron success, and NULL on an error.

B.9 fopen

Syntax :

#include <stdio.h>FILE *fopen( const char *fname, const char *mode );

The fopen() function opens a file indicated by fname and returns a stream associated with that file. Ifthere is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. forinput, output, etc)Mode Meaning– ”r” Open a text file for reading– ”w” Create a text file for writing– ”a” Append to a text file– ”rb” Open a binary file for reading– ”wb” Create a binary file for writing– ”ab” Append to a binary file– ”r+” Open a text file for read/write– ”w+” Create a text file for read/write– ”a+” Open a text file for read/write– ”rb+” Open a binary file for read/write– ”wb+” Create a binary file for read/write– ”ab+” Open a binary file for read/writeAn example :

char ch;FILE *input = fopen( "stuff", "r" );ch = getc( input );

B.10 fprintf

Syntax :

#include <stdio.h>int fprintf( FILE *stream, const char *format, ... );

Yann MORERE Licence E.E.A. Universite de Metz

46 TPs de Langage C/C++

The fprintf() function sends information (the arguments) according to the specified format to the fileindicated by stream. fprintf() works just like printf() as far as the format goes. The return value offprintf() is the number of characters outputted, or a negative number if an error occurs. An example :

char name[20] = "Mary";FILE *out;out = fopen( "output.txt", "w" );if( out != NULL )fprintf( out, "Hello %s\n", name );

Related topics : printf() and fscanf().

B.11 fputc

Syntax :

#include <stdio.h>int fputc( int ch, FILE *stream );

The function fputc() writes the given character ch to the given output stream. The return value is thecharacter, unless there is an error, in which case the return value is EOF.Related topics : fgetc(), fopen(), fprintf(), fread(), and fwrite().

B.12 fputs

Syntax :

#include <stdio.h>int fputs( const char *str, FILE *stream );

The fputs() function writes an array of characters pointed to by str to the given output stream. Thereturn value is non-negative on success, and EOF on failure.Related topics : fgets(), gets(), puts(), fprintf(), and fscanf().

B.13 fread

Syntax :

#include <stdio.h>int fread( void *buffer, size_t size, size_t num, FILE *stream );

The function fread() reads num number of objects (where each object is size bytes) and places them intothe array pointed to by buffer. The data comes from the given input stream. The return value of thefunction is the number of things read...use feof() or ferror() to figure out if an error occurs.Related topics : fwrite(), fopen(), fscanf(), fgetc(), and getc().

B.14 freopen

Syntax :

#include <stdio.h>FILE *freopen( const char *fname, const char *mode, FILE *stream );

The freopen() function is used to reassign an existing stream to a different file and mode. After a call tothis function, the given file stream will refer to fname with access given by mode. The return value offreopen() is the new stream, or NULL if there is an error.Related topics : fopen() and fclose().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 47

B.15 fscanf

Syntax :

#include <stdio.h>int fscanf( FILE *stream, const char *format, ... );

The function fscanf() reads data from the given file stream in a manner exactly like scanf(). The returnvalue of fscanf() is the number of variables that are actually assigned values, or EOF if no assignmentscould be made.Related topics : scanf() and fprintf().

B.16 fseek

Syntax :

#include <stdio.h>int fseek( FILE *stream, long offset, int origin );

The function fseek() sets the file position data for the given stream. The origin value should have one ofthe following values (defined in stdio.h) :Name Explanation– SEEK SET Seek from the start of the file– SEEK CUR Seek from the current location– SEEK END Seek from the end of the filefseek() returns zero upon success, non-zero on failure. You can use fseek() to move beyond a file, but notbefore the beginning. Using fseek() clears the EOF flag associated with that stream.Related topics : ftell(), rewind(), fopen(), fgetpos(), and fsetpos().

B.17 fsetpos

Syntax :

#include <stdio.h>int fsetpos( FILE *stream, const fpos_t *position );

The fsetpos() function moves the file position indicator for the given stream to a location specified by theposition object. fpos t is defined in stdio.h. The return value for fsetpos() is zero upon success, non-zeroon failure.Related topics : fgetpos(), fseek(), and ftell().

B.18 ftell

Syntax :

#include <stdio.h>long ftell( FILE *stream );

The ftell() function returns the current file position for stream, or -1 if an error occurs.Related topics : fseek() and fgetpos().

B.19 fwrite

Syntax :

#include <stdio.h>int fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

The fwrite() function writes, from the array buffer, count objects of size size to stream. The return valueis the number of objects written.Related topics : fread(), fscanf(), getc(), and fgetc().

Yann MORERE Licence E.E.A. Universite de Metz

48 TPs de Langage C/C++

B.20 getc

Syntax :

#include <stdio.h>int getc( FILE *stream );

The getc() function returns the next character from stream, or EOF if the end of file is reached. getc()is identical to fgetc(). For example :

char ch;FILE *input = fopen( "stuff", "r" );

ch = getc( input );while( ch != EOF ) {printf( "%c", ch );ch = getc( input );

}

Related topics : fputc(), fgetc(), putc(), and fopen().

B.21 getchar

Syntax :

#include <stdio.h>int getchar( void );

The getchar() function returns the next character from STDIN, or EOF if the end of file is reached.Related topics : fputc(), fgetc(), putc(), and fopen().

B.22 gets

Syntax :

#include <stdio.h>char *gets( char *str );

The gets() function reads characters from STDIN and loads them into str, until a newline or EOF isreached. The newline character is translated into a null termination. The return value of gets() is theread-in string, or NULL if there is an error.Related topics : fputs(), fgetc(), fgets(), and puts().

B.23 perror

Syntax :

#include <stdio.h>void perror( const char *str );

The perror() function prints str and an implementation-defined error message corresponding to the globalvariable errno.

B.24 printf

Syntax :

#include <stdio.h>int printf( const char *format, ... );

The printf() function prints output to STDOUT, according to format and other arguments passed toprintf(). The string format consists of two types of items - characters that will be printed to the screen,and format commands that define how the other arguments to printf() are displayed. Basically, you specifya format string that has text in it, as well as ”special” characters that map to the other arguments ofprintf(). For example, this code

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 49

char name[20] = "Bob";int age = 21;printf( "Hello %s, you are %d years old\n", name, age );

displays the following output :

Hello Bob, you are 21 years old

The %s means, ”insert the first argument, a string, right here.”The %d indicates that the second argument(an integer) should be placed there. There are different %-codes for different variable types, as well asoptions to limit the length of the variables and whatnot.Code Format– %c character– %d signed integers– %i signed integers– %e scientific notation, with a lowercase ”e”– %E scientific notation, with a uppercase ”E”– %f floating point– %g use %e or %f, whichever is shorter– %G use %E or %f, whichever is shorter– %o octal– %s a string of characters– %u unsigned integer– %x unsigned hexadecimal, with lowercase letters– %X unsigned hexadecimal, with uppercase letters– %p a pointer– %n the argument shall be a pointer to an integer into which is placed the number of characters written

so far– %% a ’%’ signAn integer placed between a % sign and the format command acts as a minimum field width specifier,and pads the output with spaces or zeros to make it long enough. If you want to pad with zeros, placea zero before the minimum field width specifier. You can use a precision modifier, which has differentmeanings depending on the format code being used.With %e, %E, and %f, the precision modifier lets you specify the number of decimal places desired. Forexample,

%12.6f

will display a floating number at least 12 digits wide, with six decimal places.With %g and %G, the precision modifier determines the maximum number of significant digits displayed.With %s, the precision modifer simply acts as a maximumfield length, to complement the minimum fieldlength that precedes the period. All of printf()’s output is right-justified, unless you place a minus signright after the % sign. For example,

%-12.4f

will display a floating point number with a minimum of 12 characters, 4 decimal places, and left justified.You may modify the %d, %i, %o, %u, and %x type specifiers with the letter l and the letter h to specifylong and short data types (e.g. %hd means a short integer). The %e, %f, and %g type specifiers canhave the letter l before them to indicate that a double follows. The %g, %f, and %e type specifiers canbe preceded with the character ’#’ to ensure that the decimal point will be present, even if there are nodecimal digits. The use of the ’#’ character with the %x type specifier indicates that the hexidecimalnumber should be printed with the ’0x’ prefix. The use of the ’#’ character with the %o type specifierindicates that the octal value should be displayed with a 0 prefix.You can also include constant escape sequences in the output string.The return value of printf() is the number of characters printed, or a negative number if an error occurred.Related topics : scanf() and fprintf().

B.25 putc

Syntax :

Yann MORERE Licence E.E.A. Universite de Metz

50 TPs de Langage C/C++

#include <stdio.h>int putc( int ch, FILE *stream );

The putc() function writes the character ch to stream. The return value is the character written, or EOFif there is an error. For example :

char ch;FILE *input;input = fopen( "temp.cpp", "r" );ch = getc( input );while( ch != EOF ) {printf( "%c", ch );ch = getc( input );

}

displays the contents of ”temp.cpp” to the screen.Related topics : fgetc(), fputc(), getchar(), and putchar().

B.26 putchar

Syntax :

#include <stdio.h>int putchar( int ch );

The putchar() function writes ch to STDOUT. The code

putchar( ch );

is the same as

putc( ch, STDOUT );

The return value of putchar() is the written character, or EOF if there is an error.Related topics : putc()

B.27 puts

Syntax :

#include <stdio.h>int puts( char *str );

The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure.Related topics : putc(), gets(), and printf().

B.28 remove

Syntax :

#include <stdio.h>int remove( const char *fname );

The remove() function erases the file specified by fname. The return value of remove() is zero uponsuccess, and non-zero if there is an error.Related topics : rename()

B.29 rename

Syntax :

#include <stdio.h>int rename( const char *oldfname, const char *newfname );

The function rename() changes the name of the file oldfname to newfname. The return value of rename()is zero upon success, non-zero on error.Related topics : remove()

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 51

B.30 rewind

Syntax :

#include <stdio.h>void rewind( FILE *stream );

The function rewind() moves the file position indicator to the beginning of the specified stream, alsoclearing the error and EOF flags associated with that stream.Related topics : fseek()

B.31 scanf

Syntax :

#include <stdio.h>int scanf( const char *format, ... );

The scanf() function reads input from stdin, according to the given format, and stores the data in theother arguments. It works a lot like printf(). The format string consists of control characters, whitespacecharacters, and non-whitespace characters. The control characters are preceded by aControl Character Explanation– %c a single character– %d a decimal integer– %i an integer– %e, %f, %g a floating-point number– %o an octal number– %s a string– %x a hexadecimal number– %p a pointer– %n an integer equal to the number of characters read so far– %u an unsigned integer– %[] a set of characters– %% a percent signscanf() reads the input, matching the characters from format. When a control character is read, it putsthe value in the next variable. Whitespace (tabs, spaces, etc) are skipped. Non-whitespace characters arematched to the input, then discarded. If a number comes between the % sign and the control character,then only that many characters will be converted into the variable. If scanf() encounters a set of characters,denoted by the %[] control character, then any characters found within the brackets are read into thevariable. The return value of scanf() is the number of variables that were successfully assigned values, orEOF if there is an error.Related topics : printf() and fscanf().

B.32 setbuf

Syntax :

#include <stdio.h>void setbuf( FILE *stream, char *buffer );

The setbuf() function sets stream to use buffer, or, if buffer is null, turns off buffering. If a non-standardbuffer size is used, it should by BUFSIZ characters long.Related topics : fopen(), fclose(), setvbuf(),

B.33 setvbuf

Syntax :

#include <stdio.h>int setvbuf( FILE *stream, char *buffer, int mode, size_t size );

The function setvbuf() sets the buffer for stream to be buffer, with a size of size. mode can be :

Yann MORERE Licence E.E.A. Universite de Metz

52 TPs de Langage C/C++

– IOFBF, which indicates full buffering– IOLBF, which means line buffering– IONBF, which means no bufferingRelated topics : setbuf(),

B.34 sprintf

Syntax :

#include <stdio.h>int sprintf( char *buffer, const char *format, ... );

The sprintf() function is just like printf(), except that the output is sent to buffer. The return value isthe number of characters written. For example :

char string[50];int file_number = 0;

sprintf( string, "file.%d", file_number );file_number++;output_file = fopen( string, "w" );

Related topics : printf(), fsprintf(),

B.35 sscanf

Syntax :

#include <stdio.h>int sscanf( const char *buffer, const char *format, ... );

The function sscanf() is just like scanf(), except that the input is read from buffer.Related topics : scanf(), fscanf(),

B.36 tmpfile

Syntax :

#include <stdio.h>FILE *tmpfile( void );

The function tempfile() opens a temporary file with an unique filename and returns a pointer to thatfile. If there is an error, null is returned.Related topics : tmpnam(),

B.37 tmpnam

Syntax :

#include <stdio.h>char *tmpnam( char *name );

The tmpnam() function creates an unique filename and stores it in name. tmpnam() can be called up toTMP MAX times.Related topics : tmpfile(),

B.38 ungetc

Syntax :

#include <stdio.h>int ungetc( int ch, FILE *stream );

The function ungetc() puts the character ch back in stream.Related topics : getc(),

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 53

B.39 vprintf, vfprintf, and vsprintf

Syntax :

#include <stdarg.h>#include <stdio.h>int vprintf( char *format, va_list arg_ptr );int vfprintf( FILE *stream, const char *format, va_list arg_ptr );int vsprintf( char *buffer, char *format, va_list arg_ptr );

These functions are very much like printf(), fprintf(), and sprintf(). The difference is that the argumentlist is a pointer to a list of arguments. va list is defined in STDARG.H, and is also used by va arg(). Forexample :

void error( char *fmt, ... ) {va_list args;

va_start( args, fmt );fprintf( stderr, "Error: " );vfprintf( stderr, fmt, args );fprintf( stderr, "\n" );va_end( args );exit( 1 );

}

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 55

Standard C string and character

Sources : http://www.cppreference.com/

atof() converts a string to a doubleatoi() converts a string to an integeratol() converts a string to a longisalnum() true if alphanumericisalpha() true if alphabeticiscntrl() true if control characterisdigit() true if digitisgraph() true if a graphical characterislower() true if lowercaseisprint() true if a printing characterispunct() true if punctuationisspace() true if spaceisupper() true if uppercase characterisxdigit() true if a hexidecimal charactermemchr() searches an array for the first occurance of a charactermemcmp() compares two buffersmemcpy() copies one buffer to anothermemmove() moves one buffer to anothermemset() fills a buffer with a characterstrcat() concatenates two stringsstrchr() finds the first occurance of a character in a stringstrcmp() compares two stringsstrcoll() compares two strings in accordance to the current localestrcpy() copies one string to anotherstrcspn() searches one string for any characters in anotherstrerror() returns a text version of a given error codestrlen() returns the length of a given stringstrncat() concatenates a certain amount of characters of two stringsstrncmp() compares a certain amount of characters of two stringsstrncpy() copies a certain amount of characters from one string to anotherstrpbrk() finds the first location of any character in one string, in another stringstrrchr() finds the last occurance of a character in a stringstrspn() returns the length of a substring of characters of a stringstrstr() finds the first occurance of a substring of charactersstrtod() converts a string to a doublestrtok() finds the next token in a stringstrtol() converts a string to a longstrtoul() converts a string to an unsigned longstrxfrm() converts a substring so that it can be used by string comparison functionstolower() converts a character to lowercasetoupper() converts a character to uppercase

C.1 atof

Syntax :

#include <stdlib.h>double atof( const char *str );

The function atof() converts str into a double, then returns that value. str must start with a valid number,but can be terminated with any non-numerical character, other than ”E” or ”e”. For example,

Yann MORERE Licence E.E.A. Universite de Metz

56 TPs de Langage C/C++

x = atof( "42.0is_the_answer" );

results in x being set to 42.0.Related topics : atoi() and atol().

C.2 atoi

Syntax :

#include <stdlib.h>int atoi( const char *str );

The atoi() function converts str into an integer, and returns that integer. str should start with some sortof number, and atoi() will stop reading from str as soon as a non-numerical character has been read. Forexample,

i = atoi( "512.035" );

would result in i being set to 512.Related topics : atof() and atol().

C.3 atol

Syntax :

#include <stdlib.h>long atol( const char *str );

The function atol() converts str into a long, then returns that value. atol() will read from str until itfinds any character that should not be in a long. The resulting truncated value is then converted andreturned. For example,

x = atol( "1024.0001" );

results in x being set to 1024L.Related topics : atof() and atoi().

C.4 isalnum

Syntax :

#include <ctype.h>int isalnum( int ch );

The function isalnum() returns non-zero if its argument is a numeric digit or a letter of the alphabet.Otherwise, zero is returned.

char c;scanf( "%c", &c );if( isalnum(c) )printf( "You entered the alphanumeric character %c\n", c );

Related topics : isalpha(), iscntrl(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

C.5 isalpha

Syntax :

#include <ctype.h>int isalpha( int ch );

The function isalpha() returns non-zero if its argument is a letter of the alphabet. Otherwise, zero isreturned.

char c;scanf( "%c", &c );if( isalpha(c) )printf( "You entered a letter of the alphabet\n" );

Related topics : isalnum(), iscntrl(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 57

C.6 iscntrl

Syntax :

#include <ctype.h>int iscntrl( int ch );

The iscntrl() function returns non-zero if its argument is a control character (between 0 and 0x1F orequal to 0x7F). Otherwise, zero is returned.Related topics : isalnum(), isalpha(), isdigit(), isgraph(), isprint(), ispunct(), and isspace().

C.7 isdigit

Syntax :

#include <ctype.h>int isdigit( int ch );

The function isdigit() returns non-zero if its argument is a digit between 0 and 9. Otherwise, zero isreturned.

char c;scanf( "%c", &c );if( isdigit(c) )printf( "You entered the digit %c\n", c );

Related topics : isalnum(), isalpha(), iscntrl(), isgraph(), isprint(), ispunct(), and isspace().

C.8 isgraph

Syntax :

#include <ctype.h>int isgraph( int ch );

The function isgraph() returns non-zero if its argument is any printable character other than a space (ifyou can see the character, then isgraph() will return a non-zero value). Otherwise, zero is returned.Related topics : isalnum(), isalpha(), iscntrl(), isdigit(), isprint(), ispunct(), and isspace().

C.9 islower

Syntax :

#include <ctype.h>int islower( int ch );

The islower() function returns non-zero if its argument is a lowercase letter. Otherwise, zero is returned.Related topics : isupper()

C.10 sprint

Syntax :

#include <ctype.h>int isprint( int ch );

The function isprint() returns non-zero if its argument is a printable character (including a space).Otherwise, zero is returned.Related topics : isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), ispunct(), and isspace().

Yann MORERE Licence E.E.A. Universite de Metz

58 TPs de Langage C/C++

C.11 ispunct

Syntax :

#include <ctype.h>int ispunct( int ch );

The ispunct() function returns non-zero if its argument is a printing character but neither alphanumericnor a space. Otherwise, zero is returned.Related topics : isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), isprint(), and isspace().

C.12 isspace

Syntax :

#include <ctype.h>int isspace( int ch );

The isspace() function returns non-zero if its argument is some sort of space (i.e. single space, tab, verticaltab, form feed, carriage return, or newline). Otherwise, zero is returned.Related topics : isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), and ispunct().

C.13 isupper

Syntax :

#include <ctype.h>int isupper( int ch );

The isupper() function returns non-zero if its argument is an uppercase letter. Otherwise, zero is returned.Related topics : tolower()

C.14 isxdigit

Syntax :

#include <ctype.h>int isxdigit( int ch );

The function isxdigit() returns non-zero if its argument is a hexidecimal digit (i.e. A-F, a-f, or 0-9).Otherwise, zero is returned.Related topics : isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), ispunct(), and isspace().

C.15 memchr

Syntax :

#include <string.h>void *memchr( const void *buffer, int ch, size_t count );

The memchr() function looks for the first occurrence of ch within count characters in the array pointedto by buffer. The return value points to the location of the first occurrence of ch, or NULL if ch isn’tfound. For example :

char names[] = "Alan Bob Chris X Dave";if( memchr(names,’X’,strlen(names)) == NULL )printf( "Didn’t find an X\n" );

elseprintf( "Found an X\n" );

Related topics : memcpy() and strstr().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 59

C.16 memcmp

Syntax :

#include <string.h>int memcmp( const void *buffer1, const void buffer2, size_t count );

The function memcmp() compares the first count characters of buffer1 and buffer2. The return valuesare as follows :Value Explanation– less than 0 buffer1 is less than buffer2– equal to 0 buffer1 is equal to buffer2– greater than 0 buffer1 is greater than buffer2Related topics : memchr(), memcpy(), and strcmp().

C.17 memcpy

Syntax :

#include <string.h>void *memcpy( void *to, const void *from, size_t count );

The function memcpy() copies count characters from the array from to the array to. memcpy() returnsto. The behavior of memcpy() is undefined if to and from overlap.Related topics : memmove().

C.18 memmove

Syntax :

#include <string.h>void *memmove( void *to, const void *from, size_t count );

The memmove() function is identical to memcpy(), except that it works even if to and from overlap.Related topics : memcpy().

C.19 memset

Syntax :

#include <string.h>void *memset( void *buffer, int ch, size_t count );

The function memset() copies ch into the first count characters of buffer, and returns buffer. memset()is useful for intializing a section of memory to some value. For example, this command :

memset( the_array, ’\0’, sizeof(the_array) );

is a very efficient way to set all values of the array to zero.Related topics : memcmp(), memcpy(), and memmove().

C.20 strcat

Syntax :

#include <string.h>char *strcat( char *str1, const char *str2 );

The strcat() function concatenates str2 onto the end of str1, and returns str1. For example :

printf( "Enter your name: " );scanf( "%s", name );title = strcat( name, " the Great" );printf( "Hello, %s\n", title );

Related topics : strchr(), strcmp(), and strcpy().

Yann MORERE Licence E.E.A. Universite de Metz

60 TPs de Langage C/C++

C.21 strchr

Syntax :

#include <string.h>char *strchr( const char *str, int ch );

The function strchr() returns a pointer to the first occurence of ch in str, or NULL if ch is not found.Related topics : strpbrk(), strspn(), strstr(), and strtok().

C.22 strcmp

Syntax :

#include <string.h>int strcmp( const char *str1, const char *str2 );

The function strcmp() compares str1 and str2, then returns :Return value Explanation– less than 0 str1 is less than str2– equal to 0 str1 is equal to str2– greater than 0 str1 is greater than str2For example :

printf( "Enter your name: " );scanf( "%s", name );if( strcmp( name, "Mary" ) == 0 )printf( "Hello, Dr. Mary!\n" );

Related topics : memcmp(), strchr(), strcpy(), and strncmp().

C.23 strcoll

Syntax :

#include <string.h>int strcoll( const char *str1, const char *str2 );

The strcoll() function compares str1 and str2, much like strcmp. However, strcoll() performs the compa-rison using the locale specified by the setlocale() function.

C.24 strcpy

Syntax :

#include <string.h>char *strcpy( char *to, const char *from );

The strcpy() function copies characters in the string from to the string to, including the null termination.The return value is to.Related topics : memcpy(), strchr(), strcmp(), strncmp(), and strncpy().

C.25 strcspn

Syntax :

#include <string.h>size_t strcspn( const char *str1, const char *str2 );

The function strcspn() returns the index of the first character in str1 that matches any of the charactersin str2.Related topics : strrchr(), strpbrk(), strstr(), and strtok().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 61

C.26 strerror

Syntax :

#include <string.h>char *strerror( int num );

The function strerror() returns an ”implementation defined string corresponding to num.”

C.27 strlen

Syntax :

#include <string.h>size_t strlen( char *str );

The strlen() function returns the length of str (determined by the number of characters before nulltermination).Related topics : memcpy(), strchr(), strcmp(), and strncmp().

C.28 strncat

Syntax :

#include <string.h>char *strncat( char *str1, const char *str2, size_t count );

The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination.The resulting string is returned.Related topics : strcat(), strnchr(), strncmp(), and strncpy().

C.29 strncmp

Syntax :

#include <string.h>int strncmp( const char *str1, const char *str2, size_t count );

The strncmp() function compares at most count characters of str1 and str2. The return value is asfollows :Return value Explanation– less than 0 str1 is less than str2– equal to 0 str1 is equal to str2– greater than 0 str1 is greater than str2If there are less than count characters in either string, then the comparison will stop after the first nulltermination is encountered.Related topics : strcmp(), strnchr(), and strncpy().

C.30 strncpy

Syntax :

#include <string.h>char *strncpy( char *to, const char *from, size_t count );

The strncpy() function copies at most count characters of from to the string to. If from has less thancount characters, the remainder is padded with ’\0’ characters. The return value is the resulting string.Related topics : memcpy(), strchr(), strncat(), and strncmp().

Yann MORERE Licence E.E.A. Universite de Metz

62 TPs de Langage C/C++

C.31 strpbrk

Syntax :

#include <string.h>char *strpbrk( const char *str1, const char *str2 );

The function strpbrk() returns a pointer to the first ocurrence in str1 of any character in str2, or NULLif none are present.Related topics : strspn(), strrchr(), strstr(), and strtok().

C.32 strrchr

Syntax :

#include <string.h>char *strrchr( const char *str, int ch );

The function strrchr() returns a pointer to the last occurrence of ch in str, or NULL if no match is found.Related topics : strpbrk(), strspn(), strstr(), strtok(),

C.33 strspn

Syntax :

#include <string.h>size_t strspn( const char *str1, const char *str2 );

The strspn() function returns the index of the first character in str1 that doesn’t match any characterin str2.Related topics : strpbrk(), strrchr(), strstr(), strtok(),

C.34 strstr

Syntax :

#include <string.h>char *strstr( const char *str1, const char *str2 );

The function strstr() returns a pointer to the first occurrence of str2 in str1, or NULL if no match isfound.Related topics : strchr(), strcspn(), strpbrk(), strspn(), strtok(), strrchr(),

C.35 strtod

Syntax :

#include <stdlib.h>double strtod( const char *start, char **end );

The function strtod() returns whatever it encounters first in start as a double. end is set to point atwhatever is left in start after that double. If overflow occurs, strtod() returns either HUGE VAL or-HUGE VAL.Related topics : atof()

C.36 strtok

Syntax :

#include <string.h>char *strtok( char *str1, const char *str2 );

The strtok() function returns a pointer to the next ”token” in str1, where str2 contains the delimitersthat determine the token. strtok() returns NULL if no token is found. In order to convert a string totokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after thisshould have str1 be NULL.Related topics : strchr(), strcspn(), strpbrk(), strrchr(), and strspn().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 63

C.37 strtol

Syntax :

#include <stdlib.h>long strtol( const char *start, char **end, int base );

The strtol() function returns whatever it encounters first in start as a long, doing the conversion tobase if necessary. end is set to point to whatever is left in start after the long. If the result can not berepresented by a long, then strtol() returns either LONG MAX or LONG MIN. Zero is returned uponerror.Related topics : atol().

C.38 strtoul

Syntax :

#include <stdlib.h>unsigned long strtoul( const char *start, char **end, int base );

The function strtoul() behaves exactly like strtol(), except that it returns an unsigned long rather thana mere long.Related topics : strtol()

C.39 strxfrm

Syntax :

#include <string.h>size_t strxfrm( char *str1, const char *str2, size_t num );

The strxfrm() function manipulates the first num characters of str2 and stores them in str1. The resultis such that if a strcoll() is performed on str1 and the old str2, you will get the same result as with astrcmp().Related topics : strcmp(), strcoll(),

C.40 tolower

Syntax :

#include <ctype.h>int tolower( int ch );

The function tolower() returns the lowercase version of the character ch.Related topics : toupper(),

C.41 toupper

Syntax :

#include <ctype.h>int toupper( int ch );

The toupper() function returns the uppercase version of the character ch.Related topics : tolower(),

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 65

Standard C Math

Sources : http://www.cppreference.com/

abs() absolute valueacos() arc cosineasin() arc sineatan() arc tangentatan2() arc tangent, using signs to determine quadrantsceil() the smallest integer not less than a certain valuecos() cosinecosh() hyperbolic cosinediv() returns the quotient and remainder of a divisionexp() returns ”e” raised to a given powerfabs() absolute value for floating-point numbersfloor() returns the largest integer not greater than a given valuefmod() returns the remainder of a divisionfrexp() decomposes a number into scientific notationlabs() absolute value for long integersldexp() computes a number in scientific notationldiv() returns the quotient and remainder of a division, in long integer formlog() natural logarithmlog10() natural logarithm, in base 10modf() decomposes a number into integer and fractional partspow() returns a given number raised to another numbersin() sinesinh() hyperbolic sinesqrt() square roottan() tangenttanh() hyperbolic tangent

D.1 abs

Syntax :

#include <stdlib.h>int abs( int num );

The abs() function returns the absolute value of num. For example :

int magic_number = 10;cout << "Enter a guess: ";cin >> x;cout << "Your guess was " << abs( magic_number - x ) << " away from the magic number." << endl;

Related topics : labs().

D.2 acos

Syntax :

#include <math.h>double acos( double arg );

The acos() function returns the arc cosine of arg. arg should be between -1 and 1.Related topics : asin(), atan(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

Yann MORERE Licence E.E.A. Universite de Metz

66 TPs de Langage C/C++

D.3 asin

Syntax :

#include <math.h>double asin( double arg );

The asin() function returns the arc sine of arg. arg should be between -1 and 1.Related topics : acos(), atan(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

D.4 atan

Syntax :

#include <math.h>double atan( double arg );

The function atan() returns the arc tangent of arg.Related topics : asin(), acos(), atan2(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

D.5 atan2

Syntax :

#include <math.h>double atan2( double y, double x );

The atan2() function computes the arc tangent of y/x, using the signs of the arguments to compute thequadrant of the return value.Related topics : asin(), acos(), atan(), sin(), cos(), tan(), sinh(), cosh(), and tanh().

D.6 ceil

Syntax :

#include <math.h>double ceil( double num );

The ceil() function returns the smallest integer no less than num. For example,

y = 6.04;x = ceil( y );

would set x to 7.0.Related topics : floor() and fmod().

D.7 cos

Syntax :

#include <math.h>double cos( double arg );

The cos() function returns the cosine of arg, where arg is expressed in radians.Related topics : asin(), acos(), atan(), sin(), atan2(), tan(), sinh(), cosh(), and tanh().

D.8 cosh

Syntax :

#include <math.h>double cosh( double arg );

The function cosh() returns the hyperbolic cosine of arg.Related topics : asin(), acos(), atan(), sin(), atan2(), tan(), sinh(), cos(), and tanh().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 67

D.9 div

Syntax :

#include <stdlib.h>div_t div( int numerator, int denominator );

The function div() returns the quotient and remainder of the operation numerator / denominator. Thediv t structure is defined in stdlib.h, and has at least :

int quot; // The quotientint rem; // The remainder

For example, the following code displays the quotient and remainder of x/y :

div_t temp;temp = div( x, y );printf( "%d divided by %d yields %d with a remainder of %d\n", x, y, temp.quot, temp.rem );

Related topics : ldiv().

D.10 exp

Syntax :

#include <math.h>double exp( double arg );

The exp() function returns e (2.7182818) raised to the argth power.Related topics : log().

D.11 fabs

Syntax :

#include <math.h>double fabs( double arg );

The function fabs() returns the absolute value of arg.Related topics : abs().

D.12 floor

Syntax :

#include <math.h>double floor( double arg );

The function floor() returns the largest integer not greater than arg. For example,

y = 6.04;x = floor( y );

would result in x being set to 6.0.Related topics : ceil().

D.13 fmod

Syntax :

#include <math.h>double fmod( double x, double y );

The fmod() function returns the remainder of x/y.Related topics : ceil(), floor(), and fabs().

Yann MORERE Licence E.E.A. Universite de Metz

68 TPs de Langage C/C++

D.14 frexp

Syntax :

#include <math.h>double frexp( double num, int *exp );

The function frexp() is used to decompose num into two parts : a mantissa between 0.5 and 1 (returnedby the function) and an exponent returned as exp. Scientific notation works like this :

num = mantissa * (2 ^ exp)

Related topics : ldexp().

D.15 labs

Syntax :

#include <stdlib.h>long labs( long num );

The function labs() returns the absolute value of num.Related topics : abs().

D.16 ldexp

Syntax :

#include <math.h>double ldexp( double num, int exp );

The ldexp() function returns num * (2 exp). And get this : if an overflow occurs, HUGE VAL is returned.Related topics : frexp() and modf().

D.17 ldiv

Syntax :

#include <stdlib.h>ldiv_t ldiv( long numerator, long denominator );

The ldiv() function returns the quotient and remainder of the operation numerator / denominator. Theldiv t structure is defined in stdlib.h and has at least :

long quot; // the quotientlong rem; // the remainder

Related topics : div().

D.18 log

Syntax :

#include <math.h>double log( double num );

The function log() returns the natural logarithm of num. There’s a domain error if num is negative, arange error if num is zero.Related topics : log10().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 69

D.19 log10

Syntax :

#include <math.h>double log10( double num );

The log10() function returns the base 10 logarithm for num. There’s a domain error if num is negative,a range error if num is zero.Related topics : log().

D.20 modf

Syntax :

#include <math.h>double modf( double num, double *i );

The function modf() splits num into its integer and fraction parts. It returns the fractional part andloads the integer part into i.Related topics : frexp() and ldexp().

D.21 pow

Syntax :

#include <math.h>double pow( double base, double exp );

The pow() function returns base raised to the exp power. There’s a domain error if base is zero and expis less than or equal to zero. There’s also a domain error if base is negative and exp is not an integer.There’s a range error if there’s an overflow.Related topics : exp(), log(), and sqrt().

D.22 sin

Syntax :

#include <math.h>double sin( double arg );

The function sin() returns the sine of arg, where arg is given in radians.Related topics : asin(), acos(), atan(), cosh(), atan2(), tan(), sinh(), cos(), and tanh().

D.23 sinh

Syntax :

#include <math.h>double sinh( double arg );

The function sinh() returns the hyperbolic sine of arg.Related topics : asin(), acos(), atan(), cosh(), atan2(), tan(), sin(), cos(), and tanh().

D.24 sqrt

Syntax :

#include <math.h>double sqrt( double num );

The sqrt() function returns the square root of num. If num is negative, a domain error occurs.Related topics : exp(), log(), and pow().

Yann MORERE Licence E.E.A. Universite de Metz

70 TPs de Langage C/C++

D.25 tan

Syntax :

#include <math.h>double tan( double arg );

The tan() function returns the tangent of arg, where arg is given in radians.Related topics : asin(), acos(), atan(), cosh(), atan2(), sinh(), sin(), cos(), and tanh().

D.26 tanh

Syntax :

#include <math.h>double tanh( double arg );

The function tanh() returns the hyperbolic tangent of arg.Related topics : asin(), acos(), atan(), cosh(), atan2(), tan(), sin(), cos(), and sinh().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 71

Standard C Time & Date

Sources : http://www.cppreference.com/

asctime() a textual version of the timeclock() returns the amount of time that the program has been runningctime() returns a specifically formatted version of the timedifftime() the difference between two timesgmtime() returns a pointer to the current Greenwich Mean Timelocaltime() returns a pointer to the current timemktime() returns the calendar version of a given timestrftime() returns individual elements of the date and timetime() returns the current calendar time of the system

E.1 asctime

Syntax :

#include <time.h>char *asctime( const struct tm *ptr );

The function asctime() converts the time in the struct ptr to a character string of the following format :

day month date hours:minutes:seconds year\n\0

An example :

Mon Jun 26 12:03:53 2000

Related topics : localtime(), gmtime(), time(), and ctime().

E.2 clock

Syntax :

#include <time.h>clock_t clock( void );

The clock() function returns the processor time since the program started, or -1 if that information isunavailable. To convert the return value to seconds, divide it by CLOCKS PER SECOND. (Note : ifyour compiler is POSIX compliant, then CLOCKS PER SECOND is always defined as 1000000.)Related topics : time(), asctime(), and ctime().

E.3 ctime

Syntax :

#include <time.h>char *ctime( const time_t *time );

The ctime() function converts the calendar time time to local time of the format :

day month date hours:minutes:seconds year\n\0

using ctime() is equivalent to

asctime( localtime( tp ) );

Related topics : localtime(), gmtime(), time(), and asctime().

Yann MORERE Licence E.E.A. Universite de Metz

72 TPs de Langage C/C++

E.4 difftime

Syntax :

#include <time.h>double difftime( time_t time2, time_t time1 );

The function difftime() returns time2-time1, in seconds.Related topics : localtime(), gmtime(), time(), and asctime().

E.5 gmtime

Syntax :

#include <time.h>struct tm *gmtime( const time_t *time );

The gmtime() function returns the given time in Coordinated Universal Time (usually Greenwich meantime), unless it’s not supported by the system, in which case NULL is returned. Warning !Related topics : localtime(), time(), and asctime().

E.6 localtime

Syntax :

#include <time.h>struct tm *localtime( const time_t *time );

The function localtime() converts calendar time time into local time. Warning !Related topics : gmtime(), time(), and asctime().

E.7 mktime

Syntax :

#include <time.h>time_t mktime( struct tm *time );

The mktime() function converts the local time in time to calendar time, and returns it. If there is anerror, -1 is returned.Related topics : time(), gmtime(), asctime(), and ctime().

E.8 strftime

Syntax :

#include <time.h>size_t strftime( char *str, size_t maxsize, const char *fmt, struct tm *time );

The function strftime() formats date and time information from time to a format specified by fmt, thenstores the result in str (up to maxsize characters). Certain codes may be used in fmt to specify differenttypes of time :Code Meaning :– %a abbreviated weekday name– %A full weekday name– %b abbreviated month name– %B full month name– %c the standard date and time string– %d day of the month, as a number (1-31)– %H hour, 24 hour format (0-23)– %I hour, 12 hour format (1-12)– %j day of the year, as a number (1-366)– %m month as a number (1-12)

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 73

– %M minute as a number (0-59)– %p locale’s equivalent of AM or PM– %S second as a number (0-59)– %U week of the year, sunday as the first day– %w weekday as a decimal (0-6, sunday=0)– %W week of the year, monday as the first day– %x standard date string– %X standard time string– %y year in decimal, without the century (0-99)– %Y year in decimal, with the century– %Z time zone name– %% a percent signThe strftime() function returns the number of characters put into str, or zero if an error occurs.Related topics : time(), localtime(), and gmtime().

E.9 time

Syntax :

#include <time.h>time_t time( time_t *time );

The function time() returns the current time, or -1 if there is an error. If the argument time is given,then the current time is stored in time.Related topics : localtime(), gmtime(), strftime(), ctime(),

Yann MORERE Licence E.E.A. Universite de Metz

Cette page est laissee blanche intentionnellement

TPs de Langage C/C++ 75

Standard C Memory

Sources : http://www.cppreference.com/

calloc() allocates a two-dimensional chunk of memoryfree() makes memory available for future allocationmalloc() allocates memoryrealloc() changes the size of previously allocated memory

F.1 calloc

Syntax :

#include <stdlib.h>void *calloc( size_t num, size_t size );

The calloc() function returns a pointer to space for an array of num objects, each of size size. calloc()returns NULL if there is an error.Related topics : free(), malloc(), and realloc().

F.2 free

Syntax :

#include <stdlib.h>void free( void *ptr );

The free() function deallocates the space pointed to by ptr, freeing it up for future use. ptr must havebeen used in a previous call to malloc(), calloc(), or realloc(). An example :

typedef struct data_type {int age;char name[20];

} data;

data *willy;willy = malloc( sizeof(willy) );...free( willy );

Related topics : calloc(), malloc(), and realloc().

F.3 malloc

Syntax :

#include <stdlib.h>void *malloc( size_t size );

The function malloc() returns a pointer to a chunk of space of size size, or NULL if there is an error. Anexample :

typedef struct data_type {int age;char name[20];

} data;

data *bob;

Yann MORERE Licence E.E.A. Universite de Metz

76 TPs de Langage C/C++

bob = malloc( sizeof(data) );if( bob != NULL ) {bob->age = 22;strcpy( bob->name, "Robert" );printf( "%s is %d years old\n", bob->name, bob->age );

}

Related topics : free(), realloc(), and calloc().

F.4 realloc

Syntax :

#include <stdlib.h>void *realloc( void *ptr, size_t size );

The realloc() function changes the size of the object pointed to by ptr to the given size. size can by anysize, larger or smaller than the original. The return value is a pointer to the new space, or NULL if thereis an error.Related topics : free(), malloc(), and calloc().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 77

Other standard C functions

Sources : http://www.cppreference.com/

abort() stops the programassert() stops the program if an expression isn’t trueatexit() sets a function to be called when the program exitsbsearch() perform a binary searchexit() stop the programgetenv() get enviornment information about a variablelongjmp() start execution at a certain point in the programqsort() perform a quicksortraise() send a signal to the programrand() returns a pseudorandom numbersetjmp() set execution to start at a certain pointsignal() register a function as a signal handlersrand() initialize the random number generatorsystem() perform a system callva arg() use variable length parameter lists

G.1 abort

Syntax :

#include <stdlib.h>void abort( void );

The function abort() terminates the current program. Depending on the implementation, the returnvalue can indicate failure.Related topics : exit() and atexit().

G.2 assert

Syntax :

#include <assert.h>void assert( int exp );

The assert() macro is used to test for errors. If exp evaluates to zero, assert() writes information toSTDERR and exits the program. If the macro NODEBUG is defined, the assert() macros will be ignored.Related topics : abort()

G.3 atexit

Syntax :

#include <stdlib.h>int atexit( void (*func)(void) );

The function atexit() causes the function pointed to by func to be called when the program terminates.You can make multiple calls to atexit() (at most 32) and those functions will be called in reverse orderof their establishment. The return value of atexit() is zero upon success, and nonzero on failure.Related topics : exit() and abort().

Yann MORERE Licence E.E.A. Universite de Metz

78 TPs de Langage C/C++

G.4 bsearch

Syntax :

#include <stdlib.h>void *bsearch( const void *key, const void *buf, size_t num,

size_t size, int (*compare)(const void *, const void *) );

The bsearch() function searches buf[0] to buf[num-1] for an item that matches key, using a binary search.The function compare should return negative if its first argument is less than its second, zero if equal,and positive if greater. The items in the array buf should be in ascending order. The return value ofbsearch() is a pointer to the matching item, or NULL if none is found.Related topics : qsort().

G.5 exit

Syntax :

#include <stdlib.h>void exit( int exit_code );

The exit() function stops the program. exit code is passed on to be the return value of the program,where usually zero indicates success and non-zero indicates an error.Related topics : atexit() and abort().

G.6 getenv

Syntax :

#include <stdlib.h>char *getenv( const char *name );

The function getenv() returns environmental information associated with name, and is very implemen-tation dependent. NULL is returned if no information about name is available.Related topics : system().

G.7 longjmp

Syntax :

#include <setjmp.h>void longjmp( jmp_buf envbuf, int status );

The function longjmp() causes the program to start executing code at the point of the last call tosetjmp(). envbuf is usually set through a call to setjmp(). status becomes the return value of setjmp()and can be used to figure out where longjmp() came from. status should not be set to zero.Related topics : setjmp().

G.8 qsort

Syntax :

#include <stdlib.h>void qsort( void *buf, size_t num, size_t size,

int (*compare)(const void *, const void *) );

The qsort() function sorts buf (which contains num items, each of size size) using Quicksort. The comparefunction is used to compare the items in buf. compare should return negative if the first argument isless than the second, zero if they are equal, and positive if the first argument is greater than the second.qsort() sorts buf in ascending order.Related topics : bsearch().

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 79

G.9 raise

Syntax :

#include <signal.h>int raise( int signal );

The raise() function sends the specified signal to the program. Some signals :– Signal Meaning– SIGABRT Termination error– SIGFPE Floating pointer error– SIGILL Bad instruction– SIGINT User presed CTRL-C– SIGSEGV Illegal memory access– SIGTERM Terminate programThe return value is zero upon success, nonzero on failure.Related topics : signal()

G.10 rand

Syntax :

#include <stdlib.h>int rand( void );

The function rand() returns a pseudorandom integer between zero and RAND MAX. An example :

srand( time(NULL) );for( i = 0; i < 10; i++ )printf( "Random number #%d: %d\n", i, rand() );

Related topics : srand()

G.11 setjmp

Syntax :

#include <setjmp.h>int setjmp( jmp_buf envbuf );

The setjmp() function saves the system stack in envbuf for use by a later call to longjmp(). When you firstcall setjmp(), its return value is zero. Later, when you call longjmp(), the second argument of longjmp()is what the return value of setjmp() will be. Confused ? Read about longjmp().Related topics : longjmp()

G.12 signal

Syntax :

#include <signal.h>void ( *signal( int signal, void (* func) (int)) ) (int);

The signal() function sets func to be called when signal is recieved by your program. func can be a customsignal handler, or one of these macros (defined in signal.h) :Macro Explanation– SIG DFL default signal handling– SIG IGN ignore the signalThe return value of signal() is the address of the previously defined function for this signal, or SIG ERRis there is an error.

Yann MORERE Licence E.E.A. Universite de Metz

80 TPs de Langage C/C++

G.13 srand

Syntax :

#include <stdlib.h>void srand( unsigned seed );

The function srand() is used to seed the random sequence generated by rand(). For any given seed, rand()will generate a specific ”random” sequence over and over again.

srand( time(NULL) );for( i = 0; i < 10; i++ )printf( "Random number #%d: %d\n", i, rand() );

Related topics : rand(), time().

G.14 system

Syntax :

#include <stdlib.h>int system( const char *command );

The system() function runs the given command as a system call. The return value is usually zero if thecommand executed without errors. If command is NULL, system() will test to see if there is a commandinterpreter available. Non-zero will be returned if there is a command interpreter available, zero if not.Related topics : exit(),

G.15 va arg

Syntax :

#include <stdarg.h>type va_arg( va_list argptr, type );void va_end( va_list argptr );void va_start( va_list argptr, last_parm );

The va arg() macros are used to pass a variable number of arguments to a function.First, you must have a call to va start() passing a valid va list and the mandatory first argument of thefunction. This first argument describes the number of parameters being passed. Next, you call va arg()passing the va list and the type of the argument to be returned. The return value of va arg() is thecurrent parameter. Repeat calls to va arg() for however many arguments you have. Finally, a call tova end() passing the va list is necessary for proper cleanup. For example :

int sum( int, ... );int main( void ) {int answer = sum( 4, 4, 3, 2, 1 );printf( "The answer is %d\n", answer );return( 0 );

}int sum( int num, ... ) {int answer = 0;va_list argptr;

va_start( argptr, num );for( ; num > 0; num-- )answer += va_arg( argptr, int );

va_end( argptr );return( answer );

}

This code displays 10, which is 4+3+2+1.

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 81

ASCII Chart

The following chart contains ASCII decimal, octal, hexadecimal and character codes for values from 0to 127.Sources : http://www.cppreference.com/

Decimal Octal Hex Character Description0 0 00 NUL1 1 01 SOH start of header2 2 02 STX start of text3 3 03 ETX end of text4 4 04 EOT end of transmission5 5 05 ENQ enquiry6 6 06 ACK acknowledge7 7 07 BEL bell8 10 08 BS backspace9 11 09 HT horizontal tab10 12 0A LF line feed11 13 0B VT vertical tab12 14 0C FF form feed13 15 0D CR carriage return14 16 0E SO shift out15 17 0F SI shift in16 20 10 DLE data link escape17 21 11 DC1 no assignment, but usually XON18 22 12 DC219 23 13 DC3 no assignment, but usually

XOFF20 24 14 DC421 25 15 NAK negative acknowledge22 26 16 SYN synchronous idle23 27 17 ETB end of transmission block24 30 18 CAN cancel25 31 19 EM end of medium26 32 1A SUB substitute27 33 1B ESC escape28 34 1C FS file seperator29 35 1D GS group seperator30 36 1E RS record seperator31 37 1F US unit seperator32 40 20 SPC space33 41 21 !34 42 22 ”35 43 23 #36 44 24 $37 45 25 %38 46 26 &39 47 27 ’40 50 28 (41 51 29 )

Yann MORERE Licence E.E.A. Universite de Metz

82 TPs de Langage C/C++

42 52 2A *43 53 2B +44 54 2C ,45 55 2D -46 56 2E .47 57 2F /48 60 30 049 61 31 150 62 32 251 63 33 352 64 34 453 65 35 554 66 36 655 67 37 756 70 38 857 71 39 958 72 3A :59 73 3B ;60 74 3C <61 75 3D =62 76 3E >63 77 3F ?64 100 40 @65 101 41 A66 102 42 B67 103 43 C68 104 44 D69 105 45 E70 106 46 F71 107 47 G72 110 48 H73 111 49 I74 112 4A J75 113 4B K76 114 4C L77 115 4D M78 116 4E N79 117 4F O80 120 50 P81 121 51 Q82 122 52 R83 123 53 S84 124 54 T85 125 55 U86 126 56 V87 127 57 W88 130 58 X89 131 59 Y90 132 5A Z91 133 5B [92 134 5C \93 135 5D ]

Licence E.E.A. Universite de Metz 4 mars 2004

TPs de Langage C/C++ 83

94 136 5E ˆ95 137 5F96 140 60 ‘97 141 61 a98 142 62 b99 143 63 c100 144 64 d101 145 65 e102 146 66 f103 147 67 g104 150 68 h105 151 69 i106 152 6A j107 153 6B k108 154 6C l109 155 6D m110 156 6E n111 157 6F o112 160 70 p113 161 71 q114 162 72 r115 163 73 s116 164 74 t117 165 75 u118 166 76 v119 167 77 w120 170 78 x121 171 79 y122 172 7A z123 173 7B {124 174 7C |125 175 7D }126 176 7E ˜127 177 7F DEL delete

Yann MORERE Licence E.E.A. Universite de Metz