home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / GETSTRNG.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  70 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. ** GETSTRNG.C -- Demonstration of dynamic memory allocation to
  5. **               receive string of unknown length.
  6. **
  7. ** Ron Sires 1/31/89, released to the public domain.
  8. ** Bob Stout 2/18/93, modified to use a static buffer
  9. */
  10.  
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include "editgets.h"
  14.  
  15. #define BLOCKSIZ    16
  16.  
  17. char *getstring(void)
  18. {
  19.       int    newchar;
  20.       size_t i;
  21.       static size_t bufsize = 0;
  22.       static char  *buffer  = NULL;
  23.  
  24.       /* Get chars from keyboard and put them in buffer.  */
  25.  
  26.       for (i = 0; ((newchar = getchar()) != EOF) && (newchar != '\n')
  27.             && (newchar != '\r'); ++i )
  28.       {
  29.             if (i + 1 > bufsize)
  30.             {
  31.                   /* If buffer is full, resize it. */
  32.  
  33.                   if (NULL == (buffer = realloc(buffer, bufsize + BLOCKSIZ)))
  34.                   {
  35.                         puts("\agetstrng() - Insufficient memory");
  36.  
  37.                         /* Add terminator to partial string */
  38.  
  39.                         if (buffer)
  40.                               buffer[i] = '\0';
  41.                         return buffer;
  42.                   }
  43.                   bufsize += BLOCKSIZ;
  44.             }
  45.             buffer[i] = (char) newchar;
  46.       }
  47.       buffer[i] = '\0';   /* Tack on a null-terminator. */
  48.       return buffer;
  49. }
  50.  
  51. #ifdef TEST
  52.  
  53. #include <string.h>
  54.  
  55. int main(void)
  56. {
  57.       char *string;
  58.  
  59.       puts("Enter strings of any length or <Enter> to quit\n");
  60.       do
  61.       {
  62.             string = getstring();
  63.             printf("You entered:\n\"%s\"\n\n", string);
  64.       } while (strlen(string));
  65.       free(string);
  66.       return EXIT_SUCCESS;
  67. }
  68.  
  69. #endif /* TEST */
  70.