home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fs.zip / octave / kpathsea / line.c < prev    next >
C/C++ Source or Header  |  2000-01-15  |  2KB  |  72 lines

  1. /* line.c: return the next line from a file, or NULL.
  2.  
  3. Copyright (C) 1992, 93, 95, 96 Free Software Foundation, Inc.
  4.  
  5. This library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Library General Public
  7. License as published by the Free Software Foundation; either
  8. version 2 of the License, or (at your option) any later version.
  9.  
  10. This library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. Library General Public License for more details.
  14.  
  15. You should have received a copy of the GNU Library General Public
  16. License along with this library; if not, write to the Free Software
  17. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  18.  
  19. #include <kpathsea/config.h>
  20. #include <kpathsea/line.h>
  21.  
  22. /* Allocate in increments of this size.  */
  23. #define BLOCK_SIZE 75
  24.  
  25. char *
  26. read_line (f)
  27.     FILE *f;
  28. {
  29.   int c;
  30.   unsigned limit = BLOCK_SIZE;
  31.   unsigned loc = 0;
  32.   char *line = xmalloc (limit);
  33.   
  34.   while ((c = getc (f)) != EOF && c != '\n' && c != '\r')
  35.     {
  36.       line[loc] = c;
  37.       loc++;
  38.       
  39.       /* By testing after the assignment, we guarantee that we'll always
  40.          have space for the null we append below.  We know we always
  41.          have room for the first char, since we start with BLOCK_SIZE.  */
  42.       if (loc == limit)
  43.         {
  44.           limit += BLOCK_SIZE;
  45.           line = xrealloc (line, limit);
  46.         }
  47.     }
  48.   
  49.   /* If we read anything, return it.  This can't represent a last
  50.      ``line'' which doesn't end in a newline, but so what.  */
  51.   if (c != EOF)
  52.     {
  53.       /* Terminate the string.  We can't represent nulls in the file,
  54.          either.  Again, it doesn't matter.  */
  55.       line[loc] = 0;
  56.       /* Absorb LF of a CRLF pair. */
  57.       if (c == '\r') {
  58.           c = getc (f);
  59.           if (c != '\n')
  60.               ungetc (c, f);
  61.       }
  62.     }
  63.   else /* At end of file.  */
  64.     {
  65.       free (line);
  66.       line = NULL;
  67.     }
  68.  
  69.   return line;
  70. }
  71.  
  72.