| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 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
 
 |  
#include <stdlib.h>
#include <stdio.h>
 
#define DBG 1
 
static char *getline (void)
{
   int err = 0;
   size_t size = 1;
 
/* allocation initiale de la chaine */
   char *mot = malloc (size + 1);
   if (mot != NULL)
   {
      size_t nbLettre = 0;
      int c;
 
      mot[size] = 0;
 
/* boucle tant qu'un '\n' n'a pas ete detecte */
      while ((c = getchar ()) != '\n' && c != EOF && !err)
      {
         mot[nbLettre] = c;
         assert (mot[size] == 0);
 
         nbLettre++;
         if (nbLettre == size)
         {
            char *tmp = realloc (mot, (size * 2) + 1);
 
            if (tmp != NULL)
            {
               size *= 2;
#if DBG
               printf ("realloc() %lu\n", (unsigned long) size);
#endif
               mot = tmp;
               mot[size - 1] = 0;
            }
            else
            {
               free (mot), mot = NULL;
               err = 1;
            }
         }
      }
 
/* important le caractère de fin de chaine !! */
      mot[nbLettre] = '\0';
      assert (nbLettre <= size);
      assert (mot[size] == 0);
   }
   return mot;
}
int main (int argc, char **argv)
{
   char *s = getline ();
 
   if (s != NULL)
   {
      printf ("'%s' (%lu)\n", s, strlen (s));
      free (s), s = NULL;
   }
   return 0;
} | 
Partager