Lors de la lecture d'entrées provenant de n'importe quel fichier (stdin inclus) dont vous ne connaissez pas la longueur, il est souvent préférable d'utiliser getline
plutôt que scanf
o fgets
parce que getline
se chargera automatiquement de l'allocation de mémoire pour votre chaîne de caractères, tant que vous fournissez un pointeur nul pour recevoir la chaîne saisie. Cet exemple en est une illustration :
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
printf ("\nEnter string below [ctrl + d] to quit\n");
while ((read = getline(&line, &len, stdin)) != -1) {
if (read > 0)
printf ("\n read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);
printf ("Enter string below [ctrl + d] to quit\n");
}
free (line); /* free memory allocated by getline */
return 0;
}
Les parties concernées étant :
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);
Réglage de line
a NULL
fait en sorte que getline alloue automatiquement de la mémoire. Exemple de sortie :
$ ./getline_example
Enter string below [ctrl + d] to quit
A short string to test getline!
read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!
Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL
read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL
Enter string below [ctrl + d] to quit
Ainsi, avec getline
vous n'avez pas besoin de deviner la longueur de la chaîne de caractères de votre utilisateur.