summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/getstrng.c
blob: ee6178a731f4167f542cddc40c5a2f321c737dcf (plain)
1
2
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
/*
** GETSTRNG.C -- Demonstation of dynamic memory allocation to
**               receive string of unknown length.
**
** Ron Sires 1/31/89, released to the public domain.
** Bob Stout 2/18/93, modified to use a static buffer
*/
 
#include <stdlib.h>
#include <stdio.h>
 
#define BLOCKSIZ    16
 
char *getstring(void)
{
      int    newchar;
      size_t i;
      static size_t bufsize = 0;
      static char  *buffer  = NULL;

      /* Get chars from keyboard and put them in buffer.  */

      for (i = 0; ((newchar = getchar()) != EOF) && (newchar != '\n')
            && (newchar != '\r'); ++i )
      {
            if (i + 1 > bufsize)
            {
                  /* If buffer is full, resize it. */

                  if (NULL == (buffer = realloc(buffer, bufsize + BLOCKSIZ)))
                  {
                        puts("\agetstrng() - Insufficient memory");

                        /* Add terminator to partial string */

                        if (buffer)
                              buffer[i] = '\0';
                        return buffer;
                  }
                  bufsize += BLOCKSIZ;
            }
            buffer[i] = (char) newchar;
      }
      buffer[i] = '\0';   /* Tack on a null-terminator. */
      return buffer;
}

#ifdef TEST

#include <string.h>

int main(void)
{
      char *string;

      puts("Enter strings of any length or <Enter> to quit\n");
      do
      {
            string = getstring();
            printf("You entered:\n\"%s\"\n\n", string);
      } while (strlen(string));
      free(string);
      return EXIT_SUCCESS;
}

#endif /* TEST */