T.P. Langage C/C++

Transcription

T.P. Langage C/C++
Université de Metz
T.P. Langage C/C++
Licence EEA
Année Universitaire 2003/2004
Yann MORÈRE
2
TPs de Langage C/C++
Cette série de TPs a pour objectif de vous faire coder et utiliser le langage C et C++. Il s’agira de
transcrire sous la forme d’un programme C ou C++, des algorithmes afin de réaliser les fonctions
demandées. Tous les TPs s’effectueront sous le système d’exploitation GNU/Linux.
Table des matières
Démarrage Unix & GNU/Linux
1
2
3
4
5
7
Procédure de Login . . . . . . . . . . . . . . . .
1.1
Remarque sur le mot de passe . . . . . . . . .
1.2
Pour changer de mot de passe . . . . . . . . .
1.3
Terminer votre session . . . . . . . . . . . . .
Forme et validation d’une commande . . . . . .
Commande importante : man . . . . . . . . . . .
Les éditeurs de texte . . . . . . . . . . . . . . .
4.1
vi . . . . . . . . . . . . . . . . . . . . . . . . .
4.1.1 Mode saisie . . . . . . . . . . . . . . . . . .
4.1.2 Mode commande . . . . . . . . . . . . . . .
4.1.3 Déplacement du curseur . . . . . . . . . . .
4.1.4 Commandes d’effacement et remise de texte
4.1.5 Insertion d’un fichier extérieur . . . . . . .
4.1.6 Annulation de la dernière commande . . . .
4.1.7 Recherche et remplacement . . . . . . . . .
4.1.8 Déplacement de texte . . . . . . . . . . . .
4.1.9 Mode exécution . . . . . . . . . . . . . . . .
4.2
emacs . . . . . . . . . . . . . . . . . . . . . .
4.2.1 Les modes d’édition d’emacs . . . . . . . .
4.2.2 Notion de buffer . . . . . . . . . . . . . . .
4.2.3 Commande de déplacement du curseur . . .
4.2.4 Insertion et suppression de texte . . . . . .
4.2.5 Édition simultanée de plusieurs fichiers . . .
4.2.6 Recherche et remplacement . . . . . . . . .
4.2.7 Insertion d’un fichier . . . . . . . . . . . . .
4.2.8 Suppression de fenêtres . . . . . . . . . . .
4.2.9 Sauvegarder et quitter emacs . . . . . . . .
4.3
nedit, gedit, gnotepad & kedit . . . . . . . . .
Compiler et Automatiser les tâches : make . . .
5.1
Que fait make . . . . . . . . . . . . . . . . . .
5.2
Dans le vif du sujet . . . . . . . . . . . . . . .
5.3
Pourquoi passer par make . . . . . . . . . . .
5.4
Plus loin avec GNU Make . . . . . . . . . . . .
5.5
Nouvelles règles prédéfinies . . . . . . . . . .
5.6
make all, installation et nettoyage . . . . . .
5.7
Compiler du C++ . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Sujets de TPs
21
TP C N˚1 . . . . . . . . . . . . . .
6
Polynôme du second degrés
7
Changement de Base . . .
8
Les nombres complexes . .
TP C N˚2 . . . . . . . . . . . . . .
9
Les tableaux . . . . . . . .
10
Traitement de chaı̂nes . . .
11
Le Verlan . . . . . . . . . .
12
Les palindromes . . . . . .
TP C N˚3 . . . . . . . . . . . . . .
Licence E.E.A.
9
9
10
10
10
10
11
11
11
12
12
12
12
12
12
12
13
13
13
14
14
14
14
14
14
15
15
15
17
17
17
18
18
18
19
19
.
.
.
.
.
.
.
.
.
.
Université de Metz
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
23
23
23
23
25
25
25
26
26
27
4 mars 2004
TPs de Langage C/C++
13
13.1
13.2
13.3
13.4
14
14.1
14.2
14.3
14.4
14.5
3
Résolution d’une équation f (x) =
Dichotomie . . . . . . . . . . .
Interpolation Linéaire . . . . . .
Newton . . . . . . . . . . . . .
Travail demandé . . . . . . . .
Calcul intégrale . . . . . . . . . .
La méthode des rectangles . . .
La méthode du point médian .
La méthode des trapèzes . . . .
La méthode de Simpson . . . .
Travail demandé . . . . . . . .
0
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Annexes Utiles
33
Mémento des commandes du shell
Mémento
A.1
A.2
A.3
A.4
A.5
A.6
A.7
A.8
35
des commandes du shell . . . . . . . . . . . . . . . . . . . . . .
Diffusion du présent document . . . . . . . . . . . . . . . . . .
Gestion des utilisateurs . . . . . . . . . . . . . . . . . . . . . . .
Gestion des fichiers . . . . . . . . . . . . . . . . . . . . . . . . .
Recherche et archivage de fichiers . . . . . . . . . . . . . . . . .
Gestion des processus . . . . . . . . . . . . . . . . . . . . . . . .
Traitement de chaı̂nes de caractères (pour programmation shell)
Flux de texte . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Autres outils de traitement du texte . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Librairies standards C
Standard
B.1
B.2
B.3
B.4
B.5
B.6
B.7
B.8
B.9
B.10
B.11
B.12
B.13
B.14
B.15
B.16
B.17
B.18
B.19
B.20
B.21
B.22
B.23
B.24
B.25
B.26
B.27
B.28
C Input/Output
clearerr . . . . .
fclose . . . . . .
feof . . . . . . .
ferror . . . . . .
fflush . . . . . .
fgetc . . . . . .
fgetpos . . . . .
fgets . . . . . .
fopen . . . . . .
fprintf . . . . .
fputc . . . . . .
fputs . . . . . .
fread . . . . . .
freopen . . . . .
fscanf . . . . . .
fseek . . . . . .
fsetpos . . . . .
ftell . . . . . . .
fwrite . . . . . .
getc . . . . . .
getchar . . . . .
gets . . . . . . .
perror . . . . .
printf . . . . . .
putc . . . . . .
putchar . . . .
puts . . . . . .
remove . . . . .
Yann MORÈRE
27
27
28
28
29
29
29
29
30
30
30
37
37
37
38
38
39
39
39
39
41
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.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C.35
C.36
C.37
C.38
C.39
C.40
C.41
Standard
D.1
D.2
D.3
D.4
rename . . . . . . . . . . . . .
rewind . . . . . . . . . . . . .
scanf . . . . . . . . . . . . . .
setbuf . . . . . . . . . . . . .
setvbuf . . . . . . . . . . . . .
sprintf . . . . . . . . . . . . .
sscanf . . . . . . . . . . . . .
tmpfile . . . . . . . . . . . . .
tmpnam . . . . . . . . . . . .
ungetc . . . . . . . . . . . . .
vprintf, vfprintf, and vsprintf
C string and character . . . .
atof . . . . . . . . . . . . . . .
atoi . . . . . . . . . . . . . . .
atol . . . . . . . . . . . . . . .
isalnum . . . . . . . . . . . .
isalpha . . . . . . . . . . . . .
iscntrl . . . . . . . . . . . . .
isdigit . . . . . . . . . . . . .
isgraph . . . . . . . . . . . . .
islower . . . . . . . . . . . . .
sprint . . . . . . . . . . . . . .
ispunct . . . . . . . . . . . . .
isspace . . . . . . . . . . . . .
isupper . . . . . . . . . . . . .
isxdigit . . . . . . . . . . . . .
memchr . . . . . . . . . . . .
memcmp . . . . . . . . . . . .
memcpy . . . . . . . . . . . .
memmove . . . . . . . . . . .
memset . . . . . . . . . . . .
strcat . . . . . . . . . . . . . .
strchr . . . . . . . . . . . . . .
strcmp . . . . . . . . . . . . .
strcoll . . . . . . . . . . . . .
strcpy . . . . . . . . . . . . .
strcspn . . . . . . . . . . . . .
strerror . . . . . . . . . . . . .
strlen . . . . . . . . . . . . . .
strncat . . . . . . . . . . . . .
strncmp . . . . . . . . . . . .
strncpy . . . . . . . . . . . . .
strpbrk . . . . . . . . . . . . .
strrchr . . . . . . . . . . . . .
strspn . . . . . . . . . . . . .
strstr . . . . . . . . . . . . . .
strtod . . . . . . . . . . . . .
strtok . . . . . . . . . . . . .
strtol . . . . . . . . . . . . . .
strtoul . . . . . . . . . . . . .
strxfrm . . . . . . . . . . . . .
tolower . . . . . . . . . . . . .
toupper . . . . . . . . . . . .
C Math . . . . . . . . . . . . .
abs . . . . . . . . . . . . . . .
acos . . . . . . . . . . . . . .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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
50
51
51
51
51
52
52
52
52
52
53
55
55
56
56
56
56
57
57
57
57
57
58
58
58
58
58
59
59
59
59
59
60
60
60
60
60
61
61
61
61
61
62
62
62
62
62
62
63
63
63
63
63
65
65
65
66
66
4 mars 2004
TPs de Langage C/C++
D.5
atan2 . . . . . . .
D.6
ceil . . . . . . . .
D.7
cos . . . . . . . .
D.8
cosh . . . . . . .
D.9
div . . . . . . . .
D.10 exp . . . . . . . .
D.11 fabs . . . . . . . .
D.12 floor . . . . . . .
D.13 fmod . . . . . . .
D.14 frexp . . . . . . .
D.15 labs . . . . . . . .
D.16 ldexp . . . . . . .
D.17 ldiv . . . . . . . .
D.18 log . . . . . . . .
D.19 log10 . . . . . . .
D.20 modf . . . . . . .
D.21 pow . . . . . . .
D.22 sin . . . . . . . .
D.23 sinh . . . . . . .
D.24 sqrt . . . . . . . .
D.25 tan . . . . . . . .
D.26 tanh . . . . . . .
Standard C Time & Date .
E.1
asctime . . . . . .
E.2
clock . . . . . . .
E.3
ctime . . . . . . .
E.4
difftime . . . . .
E.5
gmtime . . . . . .
E.6
localtime . . . . .
E.7
mktime . . . . . .
E.8
strftime . . . . .
E.9
time . . . . . . .
Standard C Memory . . . .
F.1
calloc . . . . . . .
F.2
free . . . . . . . .
F.3
malloc . . . . . .
F.4
realloc . . . . . .
Other standard C functions
G.1
abort . . . . . . .
G.2
assert . . . . . . .
G.3
atexit . . . . . . .
G.4
bsearch . . . . . .
G.5
exit . . . . . . . .
G.6
getenv . . . . . .
G.7
longjmp . . . . .
G.8
qsort . . . . . . .
G.9
raise . . . . . . .
G.10 rand . . . . . . .
G.11 setjmp . . . . . .
G.12 signal . . . . . . .
G.13 srand . . . . . . .
G.14 system . . . . . .
G.15 va arg . . . . . .
ASCII Chart . . . . . . . .
Yann MORÈRE
5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
66
66
66
66
67
67
67
67
67
68
68
68
68
68
69
69
69
69
69
69
70
70
71
71
71
71
72
72
72
72
72
73
75
75
75
75
76
77
77
77
77
78
78
78
78
78
79
79
79
79
80
80
80
81
Université de Metz
Cette page est laissée blanche intentionnellement
Démarrage Unix & GNU/Linux
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
1
9
Procédure de Login
Suivant la salle où vous vous trouvez (ici c’est la salle Stroustrup, en hommage au créateur du langage
C++), le type de distribution Linux installée sur la machine, de petites différences dans le mode de
connexion peuvent survenir.
Pour se connecter à l’une des machines, il faut bien entendu, avoir un accès à celle-ci c-à-d avoir un
compte.
La plupart du temps, pour se connecter, il suffit de donner son nom de login et son mot de passe au
logiciel de connexion (la plupart du temps xdm, gdm ou encore kdm). Vous obtenez une nouvelle fenêtre
ressemblant à la figure 1.
Fig. 1 – Connexion à une machine en mode graphique (ici Ulysse avec gdm)
Login : saisissez ici votre identifiant ou login et enter
Password : saisissez ici votre mot de passe (Attention les lettres frappées s’affichent sous la forme
d’étoiles) et enter.
Vous vous trouvez alors dans l’environnement LINUX, et vous avez une fenêtre du type de la figure 2.
Fig. 2 – Connexion réussie vous pouvez travailler
Toute la puissance d’un OS multitâches 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 réseau pour l’effacement de l’ancien
mot de passe.
X Le mot de passe est composé d’au moins 6 caractères et au maximum 8 dont 2 au moins ne sont pas
des lettres.
X Conseil : mélanger les lettres, chiffres, majuscules et minuscules.
Yann MORÈRE
Licence E.E.A.
Université de Metz
10
TPs de Langage C/C++
1.2
Pour changer de mot de passe
X yppasswd ou passwd et enter
X La machine vous demande l’ancien mot de passe et enter
X Elle vous demande le nouveau et enter
X Puis elle redemande le nouveau pour confirmation et enter
Si vous n’avez pas de message d’erreur, le mot de passe est alors changé.
1.3
Terminer votre session
Pour terminer votre session LINUX (se deloger), il vous suffit de terminer la session graphique à l’aide
du menu approprié. Je ne donnerai aucun détail, car ceci est très variant d’un gestionnaire de fenêtre à
un autre.
2
Forme et validation d’une commande
Une ligne de commande possède la forme générale suivante :
nom-de-commande [options] arguments
où l’option a la forme -lettre.
Exemple : Dans la commande
ls -s -i toto titils est le nom de la commande, -s -i sont les options, toto et titi sont les
arguments. Plusieurs options peuvent être regroupées derrière le signe -.
ls -si toto titi
Une ligne de commande n’est reçue et exécutée par le système qu’après validation par enter.
3
Commande importante : man
La syntaxe est la suivante :
man commande
ou
man -k commande
Cette commande affiche la page de manuel correspondante à la commande. On y trouve tous les détails
concernant son utilité, sa syntaxe et ses options.
Exemple :
réponse du système à 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 standards
as follows:
ls:
XPG4, XPG4-UNIX
Refer to the standards(5) reference page for more information about indusLicence E.E.A.
Université 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 éditeurs de texte
Un éditeur de texte est un outil pour écrire un fichier texte pur c’est à dire sans mise en forme (il ne
contient que des caractères de la table ASCII) (edit sous DOS, turbo pour la programmation TurboPascal), alors qu’un traitement de texte est un outil pour écrire et mettre en forme du texte (WordPerfect,
MS Word).
4.1
vi
vi est un éditeur vidéo, c’est à dire pleine page et interactif. Il est possible d’insérer du texte à tout
endroit dans le fichier en édition. (Cf. figure 3)
L’appel de vi s’effectue de la manière suivante :
vi
vi fichier
vi +n fichier pour se placer directement à la n-ième ligne du fichier
vi +/motif fichier pour se placer directement à la première occurrence du motif dans le fichier
X
X
X
X
Fig. 3 – Fenêtre d’édition pleine page vi
Il dispose de 3 modes de travail :
Mode commande permet les déplacements, les recherches, les destructions, etc... C’est le mode par
défaut.
Mode exécution permet l’utilisation de toutes les commandes de ed (éditeur en ligne UNIX). Mode
utilisé pour les commandes globales et les commandes gérant 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’édition :
a pour ”append” (ajout) ajoute du texte après le curseur.
A pour ”append” (ajout) ajout du texte en fin de ligne.
i pour ”insert” (insertion) insère du texte devant le curseur.
I pour ”insert” (insertion) insère du texte en début de ligne.
o pour ”open” (ouvrir) ouvre une ligne après le curseur.
O pour ”open” (ouvrir) ouvre une ligne en fin de ligne.
X
X
X
X
X
X
Yann MORÈRE
Licence E.E.A.
Université 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
Déplacement du curseur
Déplacement du curseur en mode commande :
x,j,k et l déplacent le curseur dans les 4 directions (O, S, N et E). Ces touches peuvent être remplacées
par les flèches du clavier.
w place le curseur au début du mot suivant
b place le curseur au début du mot précédent
e place le curseur à la fin du mot courant
O place le curseur en début de ligne
$ place le curseur en fin de ligne
enter place le curseur au début de la ligne suivante
^F avance le curseur d’une page
^B recule le curseur d’une page
G place le curseur en fin de fichier
n G place le curseur à la n-ième ligne du fichier
/motif / place le curseur à la prochaine occurrence du motif
mc définit une marque : elle associe la position du curseur au caractère c. On peut alors retourner d’un
autre endroit du fichier à cette position par la commande ‘c ou au début de la ligne par ’c
X
X
X
X
X
X
X
X
X
X
X
X
X
4.1.4
Commandes d’effacement et remise de texte
4.1.5
Insertion d’un fichier extérieur
X x efface le caractère sous le curseur
X dw efface un mot
X db efface le mot précédent
X D efface la fin de la ligne
X dd efface la ligne du curseur
X rc remplace le caractère courant par c
X ~ remplace une minuscule par une majuscule et vice-versa
X p réinsère le texte dernièrement effacé
X
:r fichier insère après la ligne courante un fichier extérieur
4.1.6
Annulation de la dernière commande
4.1.7
Recherche et remplacement
4.1.8
Déplacement de texte
X u annule la dernière commande effectuée
X :/motif place le curseur sur la prochaine occurrence de motif
X :s/motif /chaı̂ne/ remplace dans la ligne courante la première occurrence de motif par la chaı̂ne
X :s/motif /chaı̂ne/g remplace dans la ligne courante toute occurrence de motif par la chaı̂ne
X :1,10s/motif /chaı̂ne/g remplace toute occurrence de motif par la chaı̂ne de la première à la dixième
ligne
X :.,$%s/motif /chaı̂ne/g remplace toute occurrence de motif par la chaı̂ne depuis la ligne courante
(désignée par ".") jusqu’à la dernière ligne du fichier (désignée par "$")
X :%s/motif /chaı̂ne/g remplace dans tout le fichier toute occurrence de motif par la chaı̂ne
X mc définit le début de la section à déplacer
X se déplacer à la fin de la section à déplacer et frapper d’c, la fraction de texte est alors supprimée et
placée dans le tampon
X se déplacer à l’endroit voulu et frapper p qui insère le texte contenu dans le tampon.
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
4.1.9
13
Mode exécution
Le mode exécution est activé depuis le mode commande par la caractère ’ :’ suivi de la commande :
:w nom fichier sauvegarde le fichier nom fichier
:w sauvegarde du fichier
:wq sauvegarde et quitte vi
:q ! quitte vi sans sauvegarde
:x équivalent à :wq
X
X
X
X
X
4.2
emacs
Les principaux avantages d’emacs sont l’extensibilité, la personnalisation et l’auto-documentation. Il
possède de nombreuses fonctionnalités autres que celles de l’édition.
On peut compiler un programme, lire du courrier électronique, lire les forums, récupérer un fichier par
ftp... emacs signifie editor macros.
L’appel d’emacs s’effectue de la manière suivante :
emacs
emacs fichier
emacs +n fichier pour se placer directement à la n-ième ligne du fichier
X
X
X
Fig. 4 – Fenêtre d’édition emacs
La plupart des commandes emacs font intervenir :
la touche <CTRL> frappée en même temps qu’un autre caractère. Elle est habituellement notée C-. Par
exemple C-p désigne la touche <CTRL> frappée en même temps que p.
la touche META, existante sur la clavier, soit la touche <ALT> ou encore la touche <ESC> (dans ce cas
elle doit être relâchée avant la touche qui suit). Elle est notée M-.
X
X
4.2.1
Les modes d’édition d’emacs
Selon que l’on travaille sur un fichier texte, un programme C, un fichier de données, les besoins d’édition
sont différents. emacs propose donc plusieurs modes d’édition qui définissent un environnement de travail
adapté au type de fichier.
Modes principaux :
le mode Fundamental
le mode Text
le mode Lisp
le mode C
Il existe des modes secondaires utilisés en conjonction avec un mode principal :
le mode Fill : les lignes sont automatiquement coupées quand elles dépassent la marge droite.
X
X
X
X
X
Yann MORÈRE
Licence E.E.A.
Université de Metz
14
TPs de Langage C/C++
X le mode Abbrev : l’expansion des abréviations 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 mémoire d’emacs. A chaque ouverture de fichier un buffer portant le même nom
est créé. Les modifications n’affectent pas tout de suite le fichier sur disque mais le buffer. Il faut sauver
le fichier pour que les modifications soient effectuées sur le fichier d’origine.
4.2.3
Commande de déplacement du curseur
X C-p place le curseur sur la ligne précédente
X C-n place le curseur sur la ligne suivante
X C-f avance le curseur d’un caractère
X M-f avance le curseur à la fin du mot courant ou suivant
X C-b recule le curseur d’un caractère
X M-b recule le curseur au début du mot courant ou du précédent
X C-a place le curseur en début de ligne
X C-e place le curseur en fin de ligne
X M-< place le curseur en début de fichier
X M-> place le curseur en fin de fichier
X C-v avance la fenêtre d’un écran
X M-v recule la fenêtre d’un écran
Toutes ces commandes peuvent être envoyées avec un argument numérique n. L’argument numérique est
introduit par C-u.
La commande C-u 8 C-n avance le curseur de 8 lignes.
4.2.4
Insertion et suppression de texte
4.2.5
Édition simultanée de plusieurs fichiers
4.2.6
Recherche et remplacement
X C-d efface le caractère sur lequel se trouve le curseur
X C-k efface la fin de la ligne
X C-y réinsère le texte effacé
X C-x u annule l’effet de la dernière modification
X C-x C-f fichier crée un nouveau tampon et y place le fichier
X C-x C-b ouvre un nouveau tampon et une nouvelle fenêtre sur l’écran et y affiche la liste de tous les
tampons ouverts (cette fenêtre peut être supprimée avec C-x 1)
X C-x b tampon place la curseur dans le tampon
X C-x C-v fichier place le fichier dans le tampon courant, son contenu actuel est éliminé.
X C-x k tampon supprime le tampon (par défaut c’est le tampon courant qui est supprimé)
X C-s mot recherche la première occurrence du mot dans la suite du texte. A chaque fois que l’utilisateur
X
X
frappe une nouvelle lettre du mot, le curseur se place sur la prochaine occurrence de ce qui a été frappé.
La répétition de C-s recherche l’occurrence du mot suivant.
C-r mot a le même effet que C-s, mais la recherche se fait sur le texte qui précède.
M-% chaı̂ne nouvelle chaı̂ne remplace une chaı̂ne de caractères 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 insère le fichier à l’endroit du curseur
Pour n’insérer qu’une partie du fichier effectuer les commandes suivantes :
X C-x C-f fichier insère le fichier dans un nouveau tampon
X Placer le curseur au début de la région à insérer
X C-@ ou C-ESPACE marque le début de la région
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
15
X Placer le curseur à la fin de la région à insérer
X C-w efface la région délimitée
X C-x b revient au tampon initial
X Se placer à l’endroit voulu de l’insertion
X C-y insère le contenu du tampon auxiliaire
4.2.8
Suppression de fenêtres
X C-x 1 supprime toutes les fenêtres qui ont été ouvertes à l’exception de celle ou se trouve le curseur
4.2.9
Sauvegarder et quitter emacs
X C-x C-s sauvegarde les modifications effectuées si emacs connaı̂t le nom de fichier. Sinon l’utilisateur
est invité à entrer un nom de fichier dans le mini tampon.
X C-z quitte emacs provisoirement (le processus est suspendu). Le retour à emacs se fait en frappant fg
ou encore %emacs.
X C-x C-c quitte emacs définitivement.
4.3
nedit, gedit, gnotepad & kedit
nedit, gedit, gnotepad & kedit sont des éditeurs graphiques qui ressemblent beaucoup aux éditeurs
rencontrés sous les environnements PC, Mac, Amiga (Linux, Windows 3.xx et 9x, DOS, Mac OS, Amiga
OS). nedit, gedit, gnotepad & kedit peuvent être complètement gérés à la souris et possèdent des
menus conviviaux pour l’édition, la recherche de texte, le copier coller, la sélection de texte.
nedit utilise la bibliothèque graphique Motif, alors que gedit, gnotepad utilisent les bibliothèques de
l’environnement gnome (GLIB, GTK+) et kedit, lui est basé sur KDE et les bibliothèques QT.
Fig. 5 – Fenêtre de l’éditeur graphique nedit
Yann MORÈRE
Licence E.E.A.
Université de Metz
16
TPs de Langage C/C++
Fig. 6 – Fenêtre de l’éditeur graphique gnp
Fig. 7 – Fenêtre de l’éditeur graphique gedit
Fig. 8 – Fenêtre de l’éditeur graphique kedit
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
17
Il possède aussi des prédispositions pour la programmation. Il gère l’auto-indentation des lignes de
programmes, la gestion du nombre des parenthèses, l’affichage des mots-clés du langage.
5
Compiler et Automatiser les tâches : make
5.1
Que fait make
Sur les systèmes de la famille Unix, make remplit le même rôle que les gestionnaires de projets que
l’on retrouve dans la plupart des environnements de développement intégrés (IDE) soit sous windows
ou encore MacOS. Quel que soit son nom et sa forme, son objectif est toujours le même : centraliser
l’ensemble des fichiers et ressources dont se compose un projet, gérer les dépendances et assurer une
compilation correcte.
Ainsi si l’on modifie l’un des fichiers sources, le gestionnaire de projet en tiendra compte et saura qu’il
faut recompiler ce fichier et procéder de nouveau à une édition de liens pour obtenir un exécutable à
jour.
De plus make constitue un puissant langage de programmation, spécialisé dans la gestion des projets.
5.2
Dans le vif du sujet
Partons d’un exemple : helloworld. Mais dans notre cas il sera décomposé sur 2 fichiers sources et un
fichier d’entête.
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 manières différentes :
1. gcc helloworld.c main.c -o helloworld
2. gcc -c helloworld.c
gcc -c main.c
gcc 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 important
il devient nécessaire d’écrire un script de compilation. Dans ce cas la solution 3, utilisant make est la plus
élégante, car le programme utilise un fichier Makefile qui gère les dépendances entre les fichiers.
Nous allons donc écrire le fichier Makefile, il ressemble à ceci :
helloworld: main.o helloworld.o
gcc -o helloworld main.o helloworld.o
main.o: main.c
gcc -c main.c
helloworld.o: helloworld.c
gcc -c helloworld.c
Yann MORÈRE
Licence E.E.A.
Université de Metz
18
TPs de Langage C/C++
Un Makefile contient ainsi un ensemble de règles, dont chacune est constituée d’une ”cible”, de ”dépendances” et de commandes. Il est important de de réaliser l’indentation des lignes ci-dessus avec des
tabulations et non des espaces. Ceci occasionnerait des erreurs lors du make
La première règle définit la cible helloworld ce qui signifie que son rôle réside dans la production d’un
fichier helloworld. Cette règle possède 2 dépendances main.o et helloworld.o. Cela indique que pour
élaborer le programme helloworld, il faut préalablement disposer de ces 2 fichiers. Il vient ensuite la
commande shell qui permet de générer helloworld à partir des dépendances. Cette commande consiste
à appeler la compilation pour obtenir l’exécutable helloworld à partir des deux fichiers objets.
La règle suivante est encore plus simple, elle donne le moyen de créer le fichier objet main.o. La syntaxe
d’un Makefile se révèle donc assez simple. On peut alors l’utiliser en vue de la recompilation de notre
programme simplement e, lançant la commande make helloworld ou encore plus simplement make, car
l’outil prend par défaut la première cible trouvée.
Que va t’il se passer ? Make cherchera à générer helloworld : pour cela il vérifiera d’abord si les fichiers requis sont disponibles. S’il manque par exemple main.o, il appliquera alors la règle pour produire
ce fichier et ainsi de suite si main.o nécessitait d’autres dépendances. Une fois toutes les dépendances
satisfaites, la commande pour produire helloworld sera exécutée afin d’obtenir notre fichier exécutable.
5.3
Pourquoi passer par make
En fait, le principal intérêt de cet outil réside dans le fait qu’il n’effectue que le strict minimum. Ainsi
comme vous l’avez fait précédemment, si seul le fichier helloworld.c est modifié, lors de la recompilation
du projet, make constatera que la date de modification de helloworld.c est plus récente que la création
du fichier helloworld.o, donc il le recompilera, par contre dans le cas de main.c tout est correct, et il
n’a pas besoin de regénérer la fichier objet.
On gagne ainsi un temps considérable lors de la compilation de gros projet, en ne recompilant que ce qui
est nécessaire.
5.4
Plus loin avec GNU Make
Bien sur si make apporte un aide non négligeable poue la compilation de projet, écrire un Makefile
complet devient très vite agaçant dès que le projet devient important. Heureusement pour nous, tout
ceci peut être automatisé.
GNU make propose des mécanismes grâce auxquels il peut déduire pratiquement tout seul les règles à
appliquer. Comme il s’agit d’un langage, make gère les variables dont certaines possèdent une signification
particulière. Il est important d’en connaı̂tre au moins 8 :
– CC définit le compilateur C par défaut,
– CFLAGS définit les options à lui transmettre,
– CXX et CXXFLAGS jouent le même rôle pour le compilateur C++,
– LIBS définit les librairies à utiliser pour la compilation,
– DESTDIR définit le chemin sur lequel le programme se verra installé un fois compilé,
– @ et < représentent respectivement la cible et la dépendance courante.
De plus GNU Make possède des règles prédéfinies : ainsi il sait que par défaut il doit produire un fichier
toto.o à partir d’un fichier toto.c en invoquant le compilateur défini par la variable CC, avec les options
CFLAGS. Ainsi il est possible de simplifier le Makefile comme suit :
CC = gcc OBJS = main.o helloworld.o helloworld : $(OBJS)
$(CC) -o $(@) $(OBJS)
On donne à CC la valeur gcc et l’on garde également les dépendances dans la variable OBJS afin d’éviter
de les entrer manuellement. La seule règle que nous avons, indique comment produire helloworld à
partir des dépendances définie par la variable OBJS. On utilise alors le compilateur indiqué par CC. On
remarque aussi l’emploi de la variable @ qui, à tout instant, représente la cible de la règle où elle figure ;
dans le cas présent sa valeur est donc helloworld. Il ne s’avère plus nécessaire d’indiquer les règles pour
produire main.o et helloworld.o.
5.5
Nouvelles règles prédéfinies
Si les règles prévues dans GNU make ne vous suffisent pas, il est possible d’en redéfinir des nouvelles. Il
est alors possible de créer un fichier postscript à partir d’un fichier dvi par exemple lors de la rédaction
de document sous LATEX 2ε .
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
19
%.ps: %.dvi
dvips -ta4 -o $(@) $(<)
On exprime ici le faite, que l’on crée un fichier postscript à partir d’un fichier portant le même nom
avec le suffixe .dvi en utilisant la commande dvips.
5.6
make all, installation et nettoyage
Afin de simplifier la compilation des programmes, la règle all est très intéressante. Celle-ci lancera la
compilation complète de notre programme.
all: helloworld
Ce permet de plus d’avoir un terme générique pour lancer la compilation complète de n’importe quel
projet.
La seconde chose importante est l’installation du programme. Cette nouvelle règle est dépendante de
la compilation complète (all). Grâce à la commande make install, il sera possible de copier l’exécutable dans le sous-répertoire bin de DESTDIR ainsi que ses diverses ressources dans DESTDIR/share, la
documentation dans DESTDIR/doc et la page de manuel dans DESTDIR/man.
install: all
cp helloworld $(DESTDIR)/bin
mkdir -p $(DESTDIR)/doc/helloworld
cp manual.ps $(DESTDIR)/doc/helloworld
cp README $(DESTDIR)/doc/helloworld
cp helloworld.1 $(DESTDIR)/man/man1
Une fois l’installation faite, il ne reste plus qu’a faire le ménage des fichiers temporaires créés lors de la
compilation et qui ne servent plus. La règle clean détruira ces fichiers. Il suffira de taper make clean
pour obtenir une arborescence propre.
clean:
rm -f *.o *~
Bien sur cette règle de dépend d’aucune autre.
Le fichier makefile précédent est complété afin de pouvoir compiler, installer (dans le répertoire bin que
vous aurez créé dans votre répertoire) et nettoyer le projet helloworld.
CC= gcc
CFLAGS = -O2
DESTDIR = $(HOME)
OBJS = main.o helloworld.o
helloworld : $(OBJS)
$(CC) -o $(@) $(OBJ)
all: helloworld install: all
cp helloworld $(DESTDIR)/bin
mkdir -p $(DESTDIR)/doc/helloworld
cp 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 MORÈRE
Licence E.E.A.
Université 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.
Université de Metz
4 mars 2004
Sujets de TPs
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
23
Licence E.E.A.
TP N˚1 de Langage C
6
Polynôme du second degrés
Le but du tp est d’écrire un programme que permet de trouver les solutions d’un polynômes du second
degrés de la forme a x2 + b x + c = 0. Pour des questions de facilité on entrera les valeurs de a, b et c
directement dans des variables de type entier.
1. Écrire l’algorithme qui permettra de résoudre notre problème. Il ne faudra oublier aucun cas (tous
les types de solutions sont demandés).
2. Un menu devra permettre à l’utilisateur de choisir de quitter le programme ou de résoudre un autre
polynôme.
3. Les solutions seront présentées convenablement et le programme devra comporter les points suivants :
Écriture à l’écran du polynôme sous le forme a x2 + b x + c = 0
Informations à l’utilisateur des calculs intermédiaires nécessaires
Présentation soignée des solutions calculées
Enfin menu de demande d’abandon ou de poursuite du programme
V
V
V
V
7
Changement de Base
Le but du TP est d’écrire un programme qui permet de représenter un nombre sous différentes bases.
Rappel : Un nombre A s’écrit en base B, (B > 1) de manière unique sous la forme :
A = an B n + an−1 B n−1 + . . . + ai B i + . . . a1 B 1 + a0 B 0 =
n
X
ai B i avec ∀i ∈ [0, n], ai ≤ B − 1
i=0
Plutôt que d’écrire un nombre A dans la base B sous la forme précédente, on choisit la notation : A =
(an an−1 . . . ai . . . a1 a0 )B Pour les bases de 2 à 10 on conserve les chiffres arabes habituels (1, 2, . . . , 10).
Mais si on travaille avec des bases supérieures à 10, on ajoute généralement les lettres de l’alphabets
(A, B, C, D, . . .)
Exemple :
(4092)10 = (14634)7 = (FFC)16 = (111111111100)2
Travail demandé
1. Écrire un programme modulaire comportant un menu qui autorise l’accès aux traitements décrits
dans les points suivants
2. Le menu doit permettre d’accéder 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 écrit 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 écrit 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 où la base B, (1 < B < 33)
8
Les nombres complexes
Le but du TP est d’écrire un programme que permet de manipuler un nombre complexe. Un nombre
complexe s’écrit sous la forme A + i B. A est la partie réelle et B la partie imaginaire.
Yann MORÈRE
Licence E.E.A.
Université de Metz
24
TPs de Langage C/C++
1. Ecrire un algorithme modulaire comportant un menu qui autorise l’accès aux traitements décrits
dans les questions suivantes.
2. Le menu doit permettre d’accèder aux modules de base suivants :
un module ”LireComplexe” qui saisit un nombre complexe choisi par l’utilisateur.
un module ”EcrireComplexe” qui affiche le nombre complexe sous la forme A + iB.
un module ”NormeComplexe”qui calcule la norme du nombre complexe.
un module ”Argument” qui calcul l’argument d’un nombre complexe.
un module ”Cart2Pol”qui convertit les coordonnées cartésiennes en coordonnées polaires.
un module ”SommeComplexe” qui additionne 2 nombres complexes.
V
V
V
V
V
V
3. Ces trois derniers modules sont optionnels (pour les rapides ...) :
un module ”SoustractionComplexe” qui soustrait 2 nombres complexes.
un module ”ProduitComplexe” qui multiplie 2 nombres complexes.
un module ”DiviseComplexe” qui divise 2 nombres complexes.
V
V
V
Dans la préparation, on s’attachera à présenter les formules mathématiques qui seront utilisées dans les
différents algorithmes.
bTous à vos gommes et crayons de papier
Licence E.E.A.
Université 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 réaliser la gestion d’un réseau routier par l’intermédiaire de tableaux. On désire
relier N villes par un réseau de routes qui permet de relier n’importe quelles villes entre elles. On connaı̂t
aussi les distances qui séparent les villes entre elles.
37 Km
Dunkerque
67 Km
92 Km
Calais
135 Km
Lille
107 Km
28 Km
83 Km
45 Km
110 Km
Pas-de-Calais
30 Km
Douai
Nord
Valenciennes
Fig. 9 – Schéma du réseau routier
On définira Villes un tableau de chaı̂ne de caractères qui contiendra toutes les villes de notre réseau.
On définira ensuite un tableau à deux dimensions Distances[ville1,ville2] qui contiendra les distances
entre deux villes du tableau Villes. On supposera que les distances sont toutes distinctes entre elles et
ont des valeurs entières.
1. Écrire une procédure d’initialisation des tableaux Villes et Distances.
2. Écrire une fonction distance(ville1, ville2) qui renvoie la distance entre deux villes du tableaux.
3. Écrire une procédure qui trouve les deux villes les plus proches et affiche leurs noms.
10
Traitement de chaı̂nes
Le but du TP est d’écrire un programme C qui réalise la saisie d’une chaı̂ne de caractères ainsi que son
traitement. Les différentes procédures ou fonctions à créer sont les suivantes :
1. Le calcul du nombre de caractères alphanumériques de la chaı̂ne
2. Calcul de l’occurrence d’un caractère choisi par l’utilisateur
3. Remplacement d’un caractère par un autre dans toute la chaı̂ne
Pour la bonne marche du programme il est demandé de créer un menu qui permet d’accéder à toutes les
fonctionnalités décrites précédemment.
par exemple :
1. Calculer le nombre de caractères alphanumériques
2. Calculer l’occurrence d’un caractère
3. Remplacer un caractère
Donner votre choix :
Yann MORÈRE
Licence E.E.A.
Université de Metz
26
TPs de Langage C/C++
11
Le Verlan
Exemple : Toutes les syllabes d’un mot seront séparées 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.
– Écrire un module lisant une phrase se terminant obligatoirement par un point.
– Écrire un module effectuant la traduction.
– Écrire un module de traduction donnant le résultat 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 indifféremment à l’endroit ou à
l’envers. Généralement les signes de ponctuations tels que les espaces, les virgules, les points... ne sont
pas pris en considération (afin de simplifier le problème on écartera aussi le cas des accentuations).
Exemple :
Tu l’as trop ecrase, Cesar ce port-salut.
Travail demandé :
1. Écrire un programme modulaire comportant un menu qui autorise l’accès aux traitements décrits
dans les points suivants
2. Écrire un module lisant une phrase se terminant obligatoirement par un point (Le programme
redemandera la saisie de la phrase si celle rentrée n’est pas terminée par un point)
3. Écrire un module transformant les majuscules en minuscules dans une phrase
4. Écrire un module supprimant tous les signes de ponctuations et espaces d’une phrase
5. Écrire un module vérifiant que la phrase entrée est bien un palindrome
6. Modifier le module précédent de manière à donner la position de la première différence dans le cas
où la phrase n’est pas un palindrome
bTous à vos gommes et crayons de papier
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
27
Licence E.E.A.
TP N˚3 de Langage C
13
Résolution d’une équation f (x) = 0
Le but du TP est de trouver les racines d’une fonction quelconque donnée. Pour cela nous allons utiliser
diverse méthodes numériques.
Pour simplifier le problème nous allons nous placer dans un cas précis, l’étude de la racine de la fonction
f (x) = sin(x) − x cos(x) qui se trouve dans l’intervalle [3, 2; 4, 6].
20
15
10
5
0
-5
-10
-15
-20
0
2
4
6
8
10
12
14
16
18
20
Fig. 10 – Représentation Graphique de la fonction f (x) = sin(x) − x cos(x)
Comme les méthodes présentées sont toutes itératives et numériques il est essentiel de définir quel degrés
de précision nous voulons pour le résultat. Dans notre cas nous le choisirons égal à 10−6 .
Voici quelques conseil pour mener à bien votre TP :
1. Définir une fonction qui calcule les valeurs de la fonction étudiée.
Exemple :
double f(double x) {
return sin(x)-x*cos(x);
}
2. Définir une fonction qui calcule les valeurs de la dérivée de la fonction étudiée.
Exemple :
double df(double x) {
return x*sin(x);
}
3. Définir une fonction qui nous informe que la précision est atteinte.
Nous allons donc étudier trois méthodes numériques pour résoudre notre problème.
13.1
Dichotomie
L’algorithme est le suivant :
1. On se place sur un segment noté [u , v] tel que f (u) . f (v) < 0, la continuité 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 zéro, w est une racine de f . Sinon on
recommence en se plaçant sur celui des deux segments [u , w] ou [w , v] qui vérifient une condition
de la forme f (x) . f (y) < 0
Yann MORÈRE
Licence E.E.A.
Université de Metz
TPs de Langage C/C++
y
28
5 4
2
u=0
x
v=1
3
Fig. 11 – Résolution par Dichotomie
13.2
Interpolation Linéaire
Cette méthode est aussi appelée la méthode de la sécante. Elle est basée sur le principe suivant :
1. Partant des points u et v, on considère la sécante 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 courbe
par une droite est aussi appelée Interpolation Linéaire. Pour qu’il y aie une racine il faut, comme
précédemment que f (u) . f (v) < 0. w est donné par :
w =
³ ³
´
´
f (u)
− − f (v)v −
. v + f (v)
−u
f (v) − f (u)
v−u
y
2. On choisit alors de remplacer u ou v par w et l’on recommence jusqu’à trouver f (w) inférieur à
notre précision. On notera que si l’on choisit de remplacer u par w alors v reste constant.
v=1
u=0
x
3
2
Fig. 12 – Résolution par Interpolation Linéaire
13.3
Newton
Il s’agit d’une méthode proche de celle de la sécante, où ici la corde définie par les deux extrémités de
l’intervalle u et v est remplacée par la tangente au point u.
1. La tangente en (u , f (u)) à la courbe de f coupe l’axe des x en un point d’abscisse v = u −
f (u)
f 0 (u)
2. on remplace alors u par v et l’on recommence jusqu’à obtenir une valeur négligeable pour f (v)
3. on pourra prendre pour point de départ de u = (u + v) / 2
Licence E.E.A.
Université de Metz
4 mars 2004
29
y
TPs de Langage C/C++
v=1
u=0
2
x
3
Fig. 13 – Résolution par La méthode de Newton
13.4
Travail demandé
1. Écrire un algorithme modulaire comportant un menu qui autorisera l’accès aux différentes méthodes
de calcul
2. Les trois méthodes de calcul seront décrites dans trois fonctions séparées
3. Donner les différentes solutions trouvées par les différentes méthodes de calcul. Les comparer.
4. Répéter les calculs pour les intervalles [7; 9]et [10; 12]
5. Question subsidiaire : Faites un essai avec l’intervalle [2; 5], les résultats sont ils différents ? Pourquoi ?
14
Calcul intégrale
Le but du TP est d’écrire un programme C qui calcul l’intégrale numérique d’une fonction y = f (x)
sur un intervalle donné par l’utilisateur. Pour cela nous allons utiliser plusieurs méthodes d’intégrations
numériques.
14.1
La méthode des rectangles
pas de
calcul
L’intégrale peut s’écrire :
Y
y=f(x)
I =
¶
n−1 µ
b−a X
b−a
f a+k ×
n
n
k=0
a
b
X
n intervalles
Fig. 14 – Représentation de la méthode des rectangles
14.2
La méthode du point médian
La méthode du point médian est identique à la méthode des rectangles mais a correspond au milieu du
pas de calcul et plus à l’une des arêtes du rectangle.
Yann MORÈRE
Licence E.E.A.
Université de Metz
30
TPs de Langage C/C++
14.3
La méthode des trapèzes
pas de
calcul
L’intégrale peut s’écrire :
Ã
!
¶
n−1
X µ
b−a
b−a 1
1
f a+k×
I=
f (a) +
+ f (b)
n
2
n
2
Y
y=f(x)
k=1
a
b
X
n intervalles
Fig. 15 – Représentation de la méthode des trapèzes
14.4
La méthode de Simpson
pas de
calcul
Y
y=f(x)
a
b
X
n intervalles
L’intégrale peut s’écrire :
I=
b−a
3n
µ
µ
¶
µ
¶
µ
¶
¶
b−a
b−a
b−a
f (a) + 4 × f a +
+2×f a+2×
+4×f a+3×
+ · · · + f (b)
n
n
n
Fig. 16 – Représentation de la méthode de Simpson
14.5
Travail demandé
On fera attention au choix du pas de calcul, et on déterminera sont effet sur la précision et les temps de
calcul.
◦ Écrire un module qui calcul le résultat de f (x)
◦ Écrire un module qui détermine si un nombre est pair ou impair
◦ Écrire les modules qui calculent l’intégrale d’un fonction sur un intervalle donné par les différentes
méthodes citées. Il pourra être intéressant de créer un module par méthode.
◦ Écrire un module qui permet l’affichage d’un menu donnant les choix suivants :
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
31
1. Bornes de l’intégrale
2. Pas de calcul de l’intégrale
3. Intégrale par la méthode des rectangles
4. Intégrale par la méthode du point médian
5. Intégrale par la méthode des trapèzes
6. Intégrale par la méthode de Simpson
7. Quitter le programme
Donner votre choix :
bTous à vos gommes et crayons de papier
Yann MORÈRE
Licence E.E.A.
Université de Metz
Cette page est laissée blanche intentionnellement
Annexes Utiles
Cette page est laissée blanche intentionnellement
Mémento des commandes du shell
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
37
Mémento des commandes du shell
A.1
Diffusion du présent document
Ce document appartient à IDEALX. Il est librement diffusable dans les termes de la Licence de Documentation Libre GNU (traduit de la GNU Free Documentation License).
A.2
Gestion des utilisateurs
Syntaxe
useradd
Mnémonique
userdel
groupadd
groupdel
groupmod
passwd <utilisateur>
chfn <utilisateur>
chsh <utilisateur>
su
id
who
last
Yann MORÈRE
Password
Change Full Name
Change Shell
Super User
Signification
Ajoute un utilisateur (option -m : crée le répertoire personnel avec)
Supprime un utilisateur, son répertoire personnel et sa boı̂te aux lettres
Ajoute un groupe
Supprime un groupe
Modifie un groupe
Changer le mot de passe de <utilisateur>
Change le nom complet de <utilisateur>
Change le shell de <utilisateur>
Devient un autre utilisateur
Donne les droits du shell
Qui est connecté ?
Qui s’est connecté récemment ?
Licence E.E.A.
Université de Metz
38
TPs de Langage C/C++
A.3
Gestion des fichiers
Syntaxe
cd <répertoire>
Mnémonique
Change Directory
ls <répertoire>
ls -l <répertoire>
List
locate <motif>
mv <source> <dest>
Move
cp <source> <dest>
Copy
ln -s <source> <dest>
Link
rm <fichiers>
Remove
mkdir <répertoire>
rmdir <répertoire>
chmod
Make Directory
Remove Directory
Change Mode
chown
Change Owner
chgrp
Change Group
A.4
Signification
Place le shell dans le répertoire <répertoire>
(l’invite change en conséquence). Si <répertoire> est omis, retourne dans le répertoire
personnel ( ).
Liste les fichiers du <répertoire>.
Liste le répertoire en format long (droits
UNIX, date de dernière modification).
Localiser Liste les fichiers dont le nom contient
le <motif>, qui peut contenir des jokers (*
et ?) .
Déplace <source> vers <dest>. Si <dest> est
un répertoire, <source> est déplacé dedans
sans changer de nom.
Même sens des arguments que mv, mais fait
une copie et non un déplacement.
Crée un lien symbolique de <source> vers
<dest>. Attention : si <dest> est un répertoire relatif, il s’interprète à partir du répertoire dans lequel se trouve <source>.
Efface les fichiers seulement. rm -r : efface des
arborescences entières.
Crée un répertoire
Efface un répertoire (qui doit être vide).
Change les droits (rwxrwxrwx) d’un fichier ou
répertoire.
Change le propriétaire d’un fichier ou répertoire.
Change le groupe à qui appartient un fichier
ou répertoire.
Recherche et archivage de fichiers
Syntaxe
find
Mnémonique
xargs
cpio
Copy In and Out
tar
gzip
bzip2
du
df
Disk Usage
Disk Free
fuser
lsof
Find User
List Open Files
Licence E.E.A.
Université de Metz
Signification
Sélectionne des fichiers dans une arborescence
selon divers critères.
Exécute une même commande sur des noms
de fichiers fournis sur l’entrée standard.
Archiveur prenant les noms de fichiers sur son
entrée standard (mode de compatibilité tar
possible).
Autre archiveur.
Logiciel de compression rapide et efficace.
Logiciel de compression très lent mais très efficace.
Place disque qu’occupe une arborescence.
Place disque disponible sur toutes les partitions.
Qui a tel fichier ouvert en ce moment ?
Quels fichiers tel processus a d’ouverts en ce
moment ?
4 mars 2004
TPs de Langage C/C++
A.5
39
Gestion des processus
Syntaxe
ps
Mnémonique
Processes
kill -<sig> <pid>
killall -<sig> <nom>
top
Top ten
nice
renice
ulimit
nohup
A.6
Traitement de chaı̂nes de caractères (pour programmation shell)
Syntaxe
basename
Mnémonique
Signification
Sélectionne le dernier composant d’un chemin
d’accès.
Sélectionne le répertoire parent d’un chemin
d’accès (dernier composant exclu).
Print Working Directory Renvoie le répertoire
courant.
Substitution ou reconnaissance de motifs.
Mnémonique
Signification
Recherche le motif <expr>.
Affiche le début du texte.
Affiche la fin du texte.
Sélectionne par colonnes dans le texte.
Recherche-remplacement dans le texte.
Dit toujours la même chose.
Compte les mots.
Trie les lignes du texte.
Somme de contrôle cryptographique.
dirname
pwd
expr
A.7
Flux de texte
Syntaxe
grep <expr>
head
tail
cut
sed
yes
wc
sort
md5sum
A.8
Signification
Affiche la table des processus (options typiques : -ax).
Envoie un signal <sig> (pas nécessairement
mortel) au processus numéro <pid>.
Idem mais envoie le signal au(x) processus
dont le nom est <nom>.
Affiche les processus occupant le plus de ressources.
Lance un processus en priorité réduite.
Modifie la priorité d’un processus déjà lancé.
Restreint les maxima de ressources des processus.
Protège une commande contre la fermeture de
son terminal.
Stream Editor
Word Count
Autres outils de traitement du texte
Syntaxe
diff
Mnémonique
patch
Rustine
Yann MORÈRE
Signification
Calcule les différences entre deux fichiers (ou
entre un flux et un fichier).
Modifie un fichier texte d’après les indications
de la sortie de la commande diff.
Licence E.E.A.
Université de Metz
Cette page est laissée blanche intentionnellement
Librairies standards C
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
43
Standard C Input/Output
Sources : http://www.cppreference.com/
clearerr()
fclose()
feof()
ferror()
fflush()
fgetc()
fgetpos()
fgets()
fopen()
fprintf()
fputc()
fputs()
fread()
freopen()
fscanf()
fseek()
fsetpos()
ftell()
fwrite()
getc()
getchar()
gets()
perror()
printf()
putc()
putchar()
puts()
remove()
rename()
rewind()
scanf()
setbuf()
setvbuf()
sprintf()
sscanf()
tmpfile()
tmpnam()
ungetc()
vprintf, vfprintf, vsprintf
B.1
clears errors
close a file
true if at the end-of-file
checks for a file error
writes the contents of the output buffer
get a character from a stream
get the file position indicator
get a string of characters from a stream
open a file
print formatted output to a file
write a character to a file
write a string to a file
read from a file
open an existing stream with a different name
read formatted input from a file
move to a specific location in a file
move to a specific location in a file
returns the current file position indicator
write to a file
read a character from a file
read a character from STDIN
read a string from STDIN
displays a string version of the current error to STDERR
write formatted output to STDOUT
write a character to a stream
write a character to STDOUT
write a string to STDOUT
erase a file
rename a file
move the file position indicator to the beginning of a file
read formatted input from STDIN
set the buffer for a specific stream
set the buffer and size for a specific stream
write formatted output to a buffer
read formatted input from a buffer
return a pointer to a temporary file
return a unique filename
puts a character back into a stream
write formatted output with variable argument lists
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 MORÈRE
Licence E.E.A.
Université de Metz
44
B.2
TPs de Langage C/C++
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-zero
if 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 the
file. 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 at
the 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 if
there is an error.
Related topics : fputc(), getc(), putc(), and fopen().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
B.7
45
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 position
variable. The position variable is of type fpos t (which is defined in stdio.h) and is an object that can
hold every possible position in a FILE. fgetpos() returns zero upon success, and a non-zero value upon
failure.
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. If
fgets() reaches num - 1 characters or encounters the EOF, str will be null-terminated. fgets() returns str
on 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. If
there is an error, fopen() returns NULL. mode is used to determine how the file will be treated (i.e. for
input, 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/write
An 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 MORÈRE
Licence E.E.A.
Université de Metz
46
TPs de Langage C/C++
The fprintf() function sends information (the arguments) according to the specified format to the file
indicated by stream. fprintf() works just like printf() as far as the format goes. The return value of
fprintf() 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 the
character, 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. The
return 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 into
the array pointed to by buffer. The data comes from the given input stream. The return value of the
function 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 to
this function, the given file stream will refer to fname with access given by mode. The return value of
freopen() is the new stream, or NULL if there is an error.
Related topics : fopen() and fclose().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
B.15
47
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 return
value of fscanf() is the number of variables that are actually assigned values, or EOF if no assignments
could 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 of
the 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 file
fseek() returns zero upon success, non-zero on failure. You can use fseek() to move beyond a file, but not
before 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 the
position object. fpos t is defined in stdio.h. The return value for fsetpos() is zero upon success, non-zero
on 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 value
is the number of objects written.
Related topics : fread(), fscanf(), getc(), and fgetc().
Yann MORÈRE
Licence E.E.A.
Université 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 is
reached. The newline character is translated into a null termination. The return value of gets() is the
read-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 global
variable 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 to
printf(). 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 specify
a format string that has text in it, as well as ”special” characters that map to the other arguments of
printf(). For example, this code
Licence E.E.A.
Université 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 as
options 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 ’%’ sign
An 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, place
a zero before the minimum field width specifier. You can use a precision modifier, which has different
meanings depending on the format code being used.
With %e, %E, and %f, the precision modifier lets you specify the number of decimal places desired. For
example,
%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 field
length that precedes the period. All of printf()’s output is right-justified, unless you place a minus sign
right 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 specify
long and short data types (e.g. %hd means a short integer). The %e, %f, and %g type specifiers can
have the letter l before them to indicate that a double follows. The %g, %f, and %e type specifiers can
be preceded with the character ’#’ to ensure that the decimal point will be present, even if there are no
decimal digits. The use of the ’#’ character with the %x type specifier indicates that the hexidecimal
number should be printed with the ’0x’ prefix. The use of the ’#’ character with the %o type specifier
indicates 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 MORÈRE
Licence E.E.A.
Université 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 EOF
if 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 upon
success, 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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
B.30
51
rewind
Syntax :
#include <stdio.h>
void rewind( FILE *stream );
The function rewind() moves the file position indicator to the beginning of the specified stream, also
clearing 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 the
other arguments. It works a lot like printf(). The format string consists of control characters, whitespace
characters, and non-whitespace characters. The control characters are preceded by a
Control 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 sign
scanf() reads the input, matching the characters from format. When a control character is read, it puts
the value in the next variable. Whitespace (tabs, spaces, etc) are skipped. Non-whitespace characters are
matched 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 the
variable. The return value of scanf() is the number of variables that were successfully assigned values, or
EOF 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-standard
buffer 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 MORÈRE
Licence E.E.A.
Université de Metz
52
TPs de Langage C/C++
– IOFBF, which indicates full buffering
– IOLBF, which means line buffering
– IONBF, which means no buffering
Related 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 is
the 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 that
file. 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 to
TMP 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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
B.39
53
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 argument
list is a pointer to a list of arguments. va list is defined in STDARG.H, and is also used by va arg(). For
example :
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 MORÈRE
Licence E.E.A.
Université de Metz
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
55
Standard C string and character
Sources : http://www.cppreference.com/
atof()
atoi()
atol()
isalnum()
isalpha()
iscntrl()
isdigit()
isgraph()
islower()
isprint()
ispunct()
isspace()
isupper()
isxdigit()
memchr()
memcmp()
memcpy()
memmove()
memset()
strcat()
strchr()
strcmp()
strcoll()
strcpy()
strcspn()
strerror()
strlen()
strncat()
strncmp()
strncpy()
strpbrk()
strrchr()
strspn()
strstr()
strtod()
strtok()
strtol()
strtoul()
strxfrm()
tolower()
toupper()
C.1
converts a string to a double
converts a string to an integer
converts a string to a long
true if alphanumeric
true if alphabetic
true if control character
true if digit
true if a graphical character
true if lowercase
true if a printing character
true if punctuation
true if space
true if uppercase character
true if a hexidecimal character
searches an array for the first occurance of a character
compares two buffers
copies one buffer to another
moves one buffer to another
fills a buffer with a character
concatenates two strings
finds the first occurance of a character in a string
compares two strings
compares two strings in accordance to the current locale
copies one string to another
searches one string for any characters in another
returns a text version of a given error code
returns the length of a given string
concatenates a certain amount of characters of two strings
compares a certain amount of characters of two strings
copies a certain amount of characters from one string to another
finds the first location of any character in one string, in another string
finds the last occurance of a character in a string
returns the length of a substring of characters of a string
finds the first occurance of a substring of characters
converts a string to a double
finds the next token in a string
converts a string to a long
converts a string to an unsigned long
converts a substring so that it can be used by string comparison functions
converts a character to lowercase
converts a character to uppercase
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 MORÈRE
Licence E.E.A.
Université 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 sort
of number, and atoi() will stop reading from str as soon as a non-numerical character has been read. For
example,
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 it
finds any character that should not be in a long. The resulting truncated value is then converted and
returned. 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 is
returned.
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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
C.6
57
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 or
equal 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 is
returned.
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 (if
you 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 MORÈRE
Licence E.E.A.
Université 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 alphanumeric
nor 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, vertical
tab, 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 pointed
to by buffer. The return value points to the location of the first occurrence of ch, or NULL if ch isn’t
found. For example :
char names[] = "Alan Bob Chris X Dave";
if( memchr(names,’X’,strlen(names)) == NULL )
printf( "Didn’t find an X\n" );
else
printf( "Found an X\n" );
Related topics : memcpy() and strstr().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
C.16
59
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 values
are 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 buffer2
Related 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() returns
to. 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 MORÈRE
Licence E.E.A.
Université 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 str2
For 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 comparison 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 characters
in str2.
Related topics : strrchr(), strpbrk(), strstr(), and strtok().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
C.26
61
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 null
termination).
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 as
follows :
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 str2
If there are less than count characters in either string, then the comparison will stop after the first null
termination 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 than
count characters, the remainder is padded with ’\0’ characters. The return value is the resulting string.
Related topics : memcpy(), strchr(), strncat(), and strncmp().
Yann MORÈRE
Licence E.E.A.
Université de Metz
62
C.31
TPs de Langage C/C++
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 NULL
if 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 character
in 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 is
found.
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 at
whatever 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 delimiters
that determine the token. strtok() returns NULL if no token is found. In order to convert a string to
tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this
should have str1 be NULL.
Related topics : strchr(), strcspn(), strpbrk(), strrchr(), and strspn().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
C.37
63
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 to
base if necessary. end is set to point to whatever is left in start after the long. If the result can not be
represented by a long, then strtol() returns either LONG MAX or LONG MIN. Zero is returned upon
error.
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 than
a 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 result
is such that if a strcoll() is performed on str1 and the old str2, you will get the same result as with a
strcmp().
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 MORÈRE
Licence E.E.A.
Université de Metz
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
65
Standard C Math
Sources : http://www.cppreference.com/
abs()
acos()
asin()
atan()
atan2()
ceil()
cos()
cosh()
div()
exp()
fabs()
floor()
fmod()
frexp()
labs()
ldexp()
ldiv()
log()
log10()
modf()
pow()
sin()
sinh()
sqrt()
tan()
tanh()
D.1
absolute value
arc cosine
arc sine
arc tangent
arc tangent, using signs to determine quadrants
the smallest integer not less than a certain value
cosine
hyperbolic cosine
returns the quotient and remainder of a division
returns ”e” raised to a given power
absolute value for floating-point numbers
returns the largest integer not greater than a given value
returns the remainder of a division
decomposes a number into scientific notation
absolute value for long integers
computes a number in scientific notation
returns the quotient and remainder of a division, in long integer form
natural logarithm
natural logarithm, in base 10
decomposes a number into integer and fractional parts
returns a given number raised to another number
sine
hyperbolic sine
square root
tangent
hyperbolic tangent
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 MORÈRE
Licence E.E.A.
Université de Metz
66
D.3
TPs de Langage C/C++
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 the
quadrant 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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
D.9
67
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. The
div t structure is defined in stdlib.h, and has at least :
int quot;
int rem;
// The quotient
// 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 MORÈRE
Licence E.E.A.
Université 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 (returned
by 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 êxp). 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. The
ldiv t structure is defined in stdlib.h and has at least :
long quot;
long rem;
// the quotient
// 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, a
range error if num is zero.
Related topics : log10().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
D.19
69
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 and
loads 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 exp
is 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 MORÈRE
Licence E.E.A.
Université de Metz
70
D.25
TPs de Langage C/C++
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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
71
Standard C Time & Date
Sources : http://www.cppreference.com/
asctime()
clock()
ctime()
difftime()
gmtime()
localtime()
mktime()
strftime()
time()
E.1
a textual version of the time
returns the amount of time that the program has been running
returns a specifically formatted version of the time
the difference between two times
returns a pointer to the current Greenwich Mean Time
returns a pointer to the current time
returns the calendar version of a given time
returns individual elements of the date and time
returns the current calendar time of the system
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 is
unavailable. To convert the return value to seconds, divide it by CLOCKS PER SECOND. (Note : if
your 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 MORÈRE
Licence E.E.A.
Université de Metz
72
E.4
TPs de Langage C/C++
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 mean
time), 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 an
error, -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, then
stores the result in str (up to maxsize characters). Certain codes may be used in fmt to specify different
types 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.
Université 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 sign
The 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 MORÈRE
Licence E.E.A.
Université de Metz
Cette page est laissée blanche intentionnellement
TPs de Langage C/C++
75
Standard C Memory
Sources : http://www.cppreference.com/
calloc()
free()
malloc()
realloc()
F.1
allocates a two-dimensional chunk of memory
makes memory available for future allocation
allocates memory
changes the size of previously allocated memory
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 have
been 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. An
example :
typedef struct data_type {
int age;
char name[20];
} data;
data *bob;
Yann MORÈRE
Licence E.E.A.
Université 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 any
size, larger or smaller than the original. The return value is a pointer to the new space, or NULL if there
is an error.
Related topics : free(), malloc(), and calloc().
Licence E.E.A.
Université de Metz
4 mars 2004
TPs de Langage C/C++
77
Other standard C functions
Sources : http://www.cppreference.com/
abort()
assert()
atexit()
bsearch()
exit()
getenv()
longjmp()
qsort()
raise()
rand()
setjmp()
signal()
srand()
system()
va arg()
G.1
stops the program
stops the program if an expression isn’t true
sets a function to be called when the program exits
perform a binary search
stop the program
get enviornment information about a variable
start execution at a certain point in the program
perform a quicksort
send a signal to the program
returns a pseudorandom number
set execution to start at a certain point
register a function as a signal handler
initialize the random number generator
perform a system call
use variable length parameter lists
abort
Syntax :
#include <stdlib.h>
void abort( void );
The function abort() terminates the current program. Depending on the implementation, the return
value 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 to
STDERR 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 order
of their establishment. The return value of atexit() is zero upon success, and nonzero on failure.
Related topics : exit() and abort().
Yann MORÈRE
Licence E.E.A.
Université de Metz
78
G.4
TPs de Langage C/C++
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 of
bsearch() 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 implementation 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 to
setjmp(). 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 compare
function is used to compare the items in buf. compare should return negative if the first argument is
less 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.
Université de Metz
4 mars 2004
TPs de Langage C/C++
G.9
79
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 program
The 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 first
call 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 custom
signal handler, or one of these macros (defined in signal.h) :
Macro Explanation
– SIG DFL default signal handling
– SIG IGN ignore the signal
The return value of signal() is the address of the previously defined function for this signal, or SIG ERR
is there is an error.
Yann MORÈRE
Licence E.E.A.
Université 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 the
command executed without errors. If command is NULL, system() will test to see if there is a command
interpreter 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 the
function. 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 the
current parameter. Repeat calls to va arg() for however many arguments you have. Finally, a call to
va 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.
Université 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 0
to 127.
Sources : http://www.cppreference.com/
Decimal
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Octal
0
1
2
3
4
5
6
7
10
11
12
13
14
15
16
17
20
21
22
23
Hex
00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
10
11
12
13
Character
NUL
SOH
STX
ETX
EOT
ENQ
ACK
BEL
BS
HT
LF
VT
FF
CR
SO
SI
DLE
DC1
DC2
DC3
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
24
25
26
27
30
31
32
33
34
35
36
37
40
41
42
43
44
45
46
47
50
51
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F
20
21
22
23
24
25
26
27
28
29
DC4
NAK
SYN
ETB
CAN
EM
SUB
ESC
FS
GS
RS
US
SPC
!
”
#
$
%
&
’
(
)
Yann MORÈRE
Description
start of header
start of text
end of text
end of transmission
enquiry
acknowledge
bell
backspace
horizontal tab
line feed
vertical tab
form feed
carriage return
shift out
shift in
data link escape
no assignment, but usually XON
no assignment,
XOFF
but
usually
negative acknowledge
synchronous idle
end of transmission block
cancel
end of medium
substitute
escape
file seperator
group seperator
record seperator
unit seperator
space
Licence E.E.A.
Université de Metz
82
TPs de Langage C/C++
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
Licence E.E.A.
52
53
54
55
56
57
60
61
62
63
64
65
66
67
70
71
72
73
74
75
76
77
100
101
102
103
104
105
106
107
110
111
112
113
114
115
116
117
120
121
122
123
124
125
126
127
130
131
132
133
134
135
2A
2B
2C
2D
2E
2F
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
Université de Metz
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
4 mars 2004
TPs de Langage C/C++
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
Yann MORÈRE
136
137
140
141
142
143
144
145
146
147
150
151
152
153
154
155
156
157
160
161
162
163
164
165
166
167
170
171
172
173
174
175
176
177
83
5E
5F
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
ˆ
‘
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
˜
DEL
delete
Licence E.E.A.
Université de Metz

Documents pareils