Back to index

tetex-bin  3.0
line.c
Go to the documentation of this file.
00001 /* line.c: return the next line from a file, or NULL.
00002 
00003 Copyright (C) 1992, 93, 95, 96 Free Software Foundation, Inc.
00004 
00005 This library is free software; you can redistribute it and/or
00006 modify it under the terms of the GNU Library General Public
00007 License as published by the Free Software Foundation; either
00008 version 2 of the License, or (at your option) any later version.
00009 
00010 This library is distributed in the hope that it will be useful,
00011 but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013 Library General Public License for more details.
00014 
00015 You should have received a copy of the GNU Library General Public
00016 License along with this library; if not, write to the Free Software
00017 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
00018 
00019 #include <kpathsea/config.h>
00020 #include <kpathsea/line.h>
00021 
00022 /* Allocate in increments of this size.  */
00023 #define BLOCK_SIZE 75
00024 
00025 char *
00026 read_line P1C(FILE*, f)
00027 {
00028   int c;
00029   unsigned limit = BLOCK_SIZE;
00030   unsigned loc = 0;
00031   char *line = (char*)xmalloc (limit);
00032   
00033   while ((c = getc (f)) != EOF && c != '\n' && c != '\r')
00034     {
00035       line[loc] = c;
00036       loc++;
00037       
00038       /* By testing after the assignment, we guarantee that we'll always
00039          have space for the null we append below.  We know we always
00040          have room for the first char, since we start with BLOCK_SIZE.  */
00041       if (loc == limit)
00042         {
00043           limit += BLOCK_SIZE;
00044           line = (char*)xrealloc (line, limit);
00045         }
00046     }
00047   
00048   /* If we read anything, return it.  This can't represent a last
00049      ``line'' which doesn't end in a newline, but so what.  */
00050   if (c != EOF)
00051     {
00052       /* Terminate the string.  We can't represent nulls in the file,
00053          either.  Again, it doesn't matter.  */
00054       line[loc] = 0;
00055       /* Absorb LF of a CRLF pair. */
00056       if (c == '\r') {
00057           c = getc (f);
00058           if (c != '\n')
00059               ungetc (c, f);
00060       }
00061     }
00062   else /* At end of file.  */
00063     {
00064       free (line);
00065       line = NULL;
00066     }
00067 
00068   return line;
00069 }
00070