home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 3 / PDCD_3.iso / tex / texsrc1 / Src / lib / c / line < prev    next >
Text File  |  1993-05-02  |  2KB  |  64 lines

  1. /* line.c: return the next line from a file, or NULL.
  2.  
  3. Copyright (C) 1992 Free Software Foundation, Inc.
  4.  
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. This program 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
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with this program; if not, write to the Free Software
  17. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "config.h"
  20.  
  21.  
  22. #define BLOCK_SIZE 40
  23.  
  24. char *
  25. read_line (f)
  26.     FILE *f;
  27. {
  28.   int c;
  29.   unsigned limit = BLOCK_SIZE;
  30.   unsigned loc = 0;
  31.   char *line = (char *) xmalloc (limit);
  32.   
  33.   while ((c = getc (f)) != EOF && c != '\n')
  34.     {
  35.       line[loc] = c;
  36.       loc++;
  37.       
  38.       /* By testing after the assignment, we guarantee that we'll always
  39.          have space for the null we append below.  We know we always
  40.          have room for the first char, since we start with BLOCK_SIZE.  */
  41.       if (loc == limit)
  42.         {
  43.           limit += BLOCK_SIZE;
  44.           line = (char *) xrealloc (line, limit);
  45.         }
  46.     }
  47.   
  48.   /* If we read anything, return it.  This can't represent a last
  49.      ``line'' which doesn't end in a newline, but so what.  */
  50.   if (c != EOF)
  51.     {
  52.       /* Terminate the string.  We can't represent nulls in the file,
  53.          either.  Again, it doesn't matter.  */
  54.       line[loc] = 0;
  55.     }
  56.   else /* At end of file.  */
  57.     {
  58.       free (line);
  59.       line = NULL;
  60.     }
  61.  
  62.   return line;
  63. }
  64.