home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / cperf-2.1 / src / readline.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-11-11  |  2.0 KB  |  88 lines

  1. /* Correctly reads an arbitrarily size string.
  2.  
  3.    Copyright (C) 1989 Free Software Foundation, Inc.
  4.    written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  5.  
  6. This file is part of GNU GPERF.
  7.  
  8. GNU GPERF is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 1, or (at your option)
  11. any later version.
  12.  
  13. GNU GPERF is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with GNU GPERF; see the file COPYING.  If not, write to
  20. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. #include <stdio.h>
  23. #include "readline.h"
  24.  
  25. /* Size of each chunk. */
  26. #define CHUNK_SIZE BUFSIZ
  27.  
  28. /* Recursively fills up the buffer. */
  29.  
  30. static char *
  31. readln_aux (chunks) 
  32.      int chunks;
  33. {
  34.   char *buffered_malloc ();
  35.   char buf[CHUNK_SIZE];
  36.   register char *bufptr = buf;
  37.   register char *ptr;
  38.   int c;
  39.  
  40.   while ((c = getchar ()) != EOF && c != '\n') /* fill the current buffer */
  41.     {
  42.       *bufptr++ = c;
  43.       if (bufptr - buf >= CHUNK_SIZE) /* prepend remainder to ptr buffer */
  44.         {
  45.           if (ptr = readln_aux (chunks + 1))
  46.  
  47.             for (; bufptr != buf; *--ptr = *--bufptr);
  48.  
  49.           return ptr;
  50.         }
  51.     }
  52.  
  53.   if (c == EOF && bufptr == buf)
  54.     return NULL;
  55.  
  56.   c = (chunks * CHUNK_SIZE + bufptr - buf) + 1;
  57.  
  58.   if (ptr = buffered_malloc (c))
  59.     {
  60.  
  61.       for (*(ptr += (c - 1)) = '\0'; bufptr != buf; *--ptr = *--bufptr)
  62.         ;
  63.  
  64.       return ptr;
  65.     } 
  66.   else 
  67.     return NULL;
  68. }
  69.  
  70. /* Returns the ``next'' line, ignoring comments beginning with '#'. */
  71.  
  72. char *read_line () 
  73. {
  74.   int c;
  75.   if ((c = getchar ()) == '#')
  76.     {
  77.       while ((c = getchar ()) != '\n' && c != EOF)
  78.         ;
  79.  
  80.       return c != EOF ? read_line () : NULL;
  81.     }
  82.   else
  83.     {
  84.       ungetc (c, stdin);
  85.       return readln_aux (0);
  86.     }
  87. }
  88.