home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume20 / gperf / part01 / cperf / src / readline.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-10-18  |  2.0 KB  |  87 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 buf[CHUNK_SIZE];
  35.   register char *bufptr = buf;
  36.   register char *ptr;
  37.   int c;
  38.  
  39.   while ((c = getchar ()) != EOF && c != '\n') /* fill the current buffer */
  40.     {
  41.       *bufptr++ = c;
  42.       if (bufptr - buf >= CHUNK_SIZE) /* prepend remainder to ptr buffer */
  43.         {
  44.           if (ptr = readln_aux (chunks + 1))
  45.  
  46.             for (; bufptr != buf; *--ptr = *--bufptr);
  47.  
  48.           return ptr;
  49.         }
  50.     }
  51.  
  52.   if (c == EOF && bufptr == buf)
  53.     return NULL;
  54.  
  55.   c = (chunks * CHUNK_SIZE + bufptr - buf) + 1;
  56.  
  57.   if (ptr = (char *) xmalloc (c))
  58.     {
  59.  
  60.       for (*(ptr += (c - 1)) = '\0'; bufptr != buf; *--ptr = *--bufptr)
  61.         ;
  62.  
  63.       return ptr;
  64.     } 
  65.   else 
  66.     return NULL;
  67. }
  68.  
  69. /* Returns the ``next'' line, ignoring comments beginning with '#'. */
  70.  
  71. char *read_line () 
  72. {
  73.   int c;
  74.   if ((c = getchar ()) == '#')
  75.     {
  76.       while ((c = getchar ()) != '\n' && c != EOF)
  77.         ;
  78.  
  79.       return c != EOF ? read_line () : NULL;
  80.     }
  81.   else
  82.     {
  83.       ungetc (c, stdin);
  84.       return readln_aux (0);
  85.     }
  86. }
  87.