(root)/
attr-2.5.1/
libmisc/
next_line.c
       1  /*
       2    Copyright (C) 2009  Andreas Gruenbacher <agruen@suse.de>
       3  
       4    This program is free software: you can redistribute it and/or modify it
       5    under the terms of the GNU Lesser General Public License as published by
       6    the Free Software Foundation, either version 2.1 of the License, or
       7    (at your option) any later version.
       8  
       9    This program is distributed in the hope that it will be useful,
      10    but WITHOUT ANY WARRANTY; without even the implied warranty of
      11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12    GNU Lesser General Public License for more details.
      13  
      14    You should have received a copy of the GNU Lesser General Public License
      15    along with this program.  If not, see <http://www.gnu.org/licenses/>.
      16   */
      17  
      18  #include "config.h"
      19  
      20  #include <stdio.h>
      21  #include <string.h>
      22  #include <limits.h>
      23  #include <unistd.h>
      24  #include "misc.h"
      25  
      26  #define LINE_SIZE getpagesize()
      27  
      28  char *next_line(FILE *file)
      29  {
      30  	static char *line;
      31  	static size_t line_size;
      32  	char *c;
      33  	int eol = 0;
      34  
      35  	if (!line) {
      36  		if (high_water_alloc((void **)&line, &line_size, LINE_SIZE))
      37  			return NULL;
      38  	}
      39  	c = line;
      40  	do {
      41  		if (!fgets(c, line_size - (c - line), file))
      42  			return NULL;
      43  		c = strrchr(c, '\0');
      44  		while (c > line && (*(c-1) == '\n' || *(c-1) == '\r')) {
      45  			c--;
      46  			*c = '\0';
      47  			eol = 1;
      48  		}
      49  		if (feof(file))
      50  			break;
      51  		if (!eol) {
      52  			if (high_water_alloc((void **)&line, &line_size,
      53  					     2 * line_size))
      54  				return NULL;
      55  			c = strrchr(line, '\0');
      56  		}
      57  	} while (!eol);
      58  	return line;
      59  }